about summary refs log tree commit diff stats
path: root/linux/apps/factorial.mu
diff options
context:
space:
mode:
authorKartik K. Agaram <vc@akkartik.com>2021-07-16 08:09:42 -0700
committerKartik K. Agaram <vc@akkartik.com>2021-07-16 08:28:56 -0700
commit44d26b77c45668c9b0c99894a4294cec004361fe (patch)
tree68a5dcd4971873efd4ce184e9bf9a531c2161813 /linux/apps/factorial.mu
parentac45f097153afd3a89f43886e4124c5b2c26b98a (diff)
downloadmu-44d26b77c45668c9b0c99894a4294cec004361fe.tar.gz
.
Diffstat (limited to 'linux/apps/factorial.mu')
-rw-r--r--linux/apps/factorial.mu60
1 files changed, 60 insertions, 0 deletions
diff --git a/linux/apps/factorial.mu b/linux/apps/factorial.mu
new file mode 100644
index 00000000..959d3bc0
--- /dev/null
+++ b/linux/apps/factorial.mu
@@ -0,0 +1,60 @@
+# compute the factorial of 5, and return the result in the exit code
+#
+# To run:
+#   $ ./translate apps/factorial.mu
+#   $ ./a.elf
+#   $ echo $?
+#   120
+#
+# You can also run the automated test suite:
+#   $ ./a.elf test
+# 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.
+#
+# Compare factorial4.subx
+
+fn factorial n: int -> _/eax: int {
+  compare n, 1
+  # if (n <= 1) return 1
+  {
+    break-if->
+    return 1
+  }
+  # 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
+}
+
+fn test-factorial {
+  var result/eax: int <- factorial 5
+  check-ints-equal result, 0x78, "F - test-factorial"
+}
+
+fn main args-on-stack: (addr array addr array byte) -> _/ebx: int {
+  var args/eax: (addr array addr array byte) <- copy args-on-stack
+  # len = length(args)
+  var len/ecx: int <- length args
+  # 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
+  }
+  return 0
+}