mu/archive/1.vm/factorial.mu

34 lines
529 B
Forth
Raw Permalink Normal View History

# example program: compute the factorial of 5
def main [
local-scope
x:num <- factorial 5
$print [result: ], x, [
]
]
def factorial n:num -> result:num [
local-scope
2017-12-04 07:25:40 +00:00
load-inputs
{
# if n=0 return 1
zero?:bool <- equal n, 0
break-unless zero?
return 1
}
2015-06-25 20:05:27 +00:00
# return n * factorial(n-1)
x:num <- subtract n, 1
subresult:num <- factorial x
2015-11-11 17:13:40 +00:00
result <- multiply subresult, n
]
# unit test
scenario factorial-test [
run [
1:num <- factorial 5
]
2015-05-26 18:26:10 +00:00
memory-should-contain [
1 <- 120
]
]