musique/examples/factorial.mq
2022-10-27 22:32:20 +02:00

31 lines
919 B
Plaintext

----------------------------------------------------------------------------
This example shows how to implement factorial operation using different
implementation techniques, showing how one can iterate and accumulate
using Musique programming language
----------------------------------------------------------------------------
-- Calculate factorial using recursive approach
factorial_recursive := (n |
if (n <= 1)
1
(n * (factorial_recursive (n-1)))
),
-- Calculate factorial using iterative approach
factorial_iterative := (n |
x := 1,
for (range 1 (n+1)) (i | x *= i),
x
),
-- Calculate factorial using composition of functions
factorial := (n | fold '* 1 (1 + up n)),
-- Gather all functions into array, and iterate over it
-- This allows to reduce repeatition of this test case
for (factorial_recursive, factorial_iterative, factorial) ( factorial |
for (up 10) ( n |
say (factorial (n)),
)
),