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
|
|
|
|
factorial_recursive := [n |
|
|
|
|
if (n <= 1)
|
|
|
|
[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-09-18 14:50:20 +02:00
|
|
|
factorial_iterative := [n |
|
|
|
|
x := 1;
|
2022-09-19 22:16:38 +02:00
|
|
|
for (range 1 (n+1)) [i|x *= i];
|
2022-06-06 04:22:59 +02:00
|
|
|
x
|
|
|
|
];
|
2022-09-19 22:16:38 +02:00
|
|
|
|
|
|
|
-- Calculate factorial using composition of functions
|
|
|
|
factorial := [n| fold (1 + up n) 1 '*];
|
|
|
|
|
|
|
|
-- 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));
|
|
|
|
];
|
|
|
|
];
|