2022-09-19 22:16:38 +02:00
|
|
|
----------------------------------------------------------------------------
|
|
|
|
This example shows how to implement factorial operation using different
|
|
|
|
implementation techniques, showing how one can iterate and accumulate
|
|
|
|
using Musique programming language
|
|
|
|
----------------------------------------------------------------------------
|
2022-05-17 16:10:56 +02:00
|
|
|
|
2022-09-19 22:16:38 +02:00
|
|
|
-- Calculate factorial using recursive approach
|
2022-10-25 16:10:34 +02:00
|
|
|
factorial_recursive := (n |
|
2022-09-19 22:16:38 +02:00
|
|
|
if (n <= 1)
|
2022-10-25 16:10:34 +02:00
|
|
|
(| 1)
|
|
|
|
(| n * (factorial_recursive (n-1)))
|
|
|
|
);
|
2022-06-06 04:22:59 +02:00
|
|
|
|
2022-09-19 22:16:38 +02:00
|
|
|
-- Calculate factorial using iterative approach
|
2022-10-25 16:10:34 +02:00
|
|
|
factorial_iterative := (n |
|
2022-09-18 14:50:20 +02:00
|
|
|
x := 1;
|
2022-10-25 16:10:34 +02:00
|
|
|
for (range 1 (n+1)) (i | x *= i);
|
2022-06-06 04:22:59 +02:00
|
|
|
x
|
2022-10-25 16:10:34 +02:00
|
|
|
);
|
2022-09-19 22:16:38 +02:00
|
|
|
|
|
|
|
-- Calculate factorial using composition of functions
|
2022-10-25 16:10:34 +02:00
|
|
|
factorial := (n | fold (1 + up n) 1 '*);
|
2022-09-19 22:16:38 +02:00
|
|
|
|
|
|
|
-- Gather all functions into array, and iterate over it
|
|
|
|
-- This allows to reduce repeatition of this test case
|
2022-10-25 16:10:34 +02:00
|
|
|
for (factorial_recursive; factorial_iterative; factorial) ( factorial |
|
|
|
|
for (up 10) ( n |
|
2022-09-19 22:16:38 +02:00
|
|
|
say (factorial (n));
|
2022-10-25 16:10:34 +02:00
|
|
|
)
|
|
|
|
);
|