musique/examples/factorial.mq

31 lines
919 B
Plaintext
Raw Permalink Normal View History

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 |
2022-09-19 22:16:38 +02:00
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
factorial_iterative := (n |
x := 1,
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 (1 + up n)),
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
for (factorial_recursive, factorial_iterative, factorial) ( factorial |
for (up 10) ( n |
say (factorial (n)),
)
),