mu/linux/factorial.mu

61 lines
1.4 KiB
Forth
Raw Normal View History

2020-03-14 08:25:34 +00:00
# compute the factorial of 5, and return the result in the exit code
#
# To run:
2021-03-04 08:11:23 +00:00
# $ ./translate factorial.mu
2020-03-14 08:25:34 +00:00
# $ ./a.elf
# $ echo $?
# 120
#
# You can also run the automated test suite:
# $ ./a.elf test
2020-10-14 20:42:03 +00:00
# Expected output:
# ........
# Every '.' indicates a passing test. Failing tests get a 'F'.
# There's only one test in this file, but you'll also see tests running from
# Mu's standard library.
2020-03-14 08:06:27 +00:00
#
2021-03-30 01:47:52 +00:00
# Compare factorial4.subx
2020-03-02 16:20:20 +00:00
2020-11-02 06:02:13 +00:00
fn factorial n: int -> _/eax: int {
2020-10-14 19:22:32 +00:00
compare n, 1
2020-11-02 06:02:13 +00:00
# if (n <= 1) return 1
2020-03-02 16:20:20 +00:00
{
break-if->
2020-11-02 06:02:13 +00:00
return 1
2020-03-02 16:20:20 +00:00
}
2020-11-02 06:02:13 +00:00
# n > 1; return n * factorial(n-1)
var tmp/ecx: int <- copy n
tmp <- decrement
var result/eax: int <- factorial tmp
result <- multiply n
return result
2020-03-02 16:20:20 +00:00
}
fn test-factorial {
var result/eax: int <- factorial 5
2020-10-14 19:22:32 +00:00
check-ints-equal result, 0x78, "F - test-factorial"
2020-03-02 16:20:20 +00:00
}
fn main args-on-stack: (addr array addr array byte) -> _/ebx: int {
var args/eax: (addr array addr array byte) <- copy args-on-stack
2020-10-14 19:00:19 +00:00
# len = length(args)
var len/ecx: int <- length args
2020-11-02 06:02:13 +00:00
# if (len <= 1) return factorial(5)
compare len, 1
{
break-if->
var exit-status/eax: int <- factorial 5
return exit-status
}
# if (args[1] == "test") run-tests()
var tmp2/ecx: (addr addr array byte) <- index args, 1
var tmp3/eax: boolean <- string-equal? *tmp2, "test"
compare tmp3, 0
{
break-if-=
run-tests
# TODO: get at Num-test-failures somehow
}
2020-11-02 06:02:13 +00:00
return 0
2020-01-30 07:17:36 +00:00
}