summaryrefslogtreecommitdiff
path: root/examples/recursion.ts
diff options
context:
space:
mode:
authorKai Stevenson <kai@kaistevenson.com>2025-11-06 21:12:44 -0800
committerKai Stevenson <kai@kaistevenson.com>2025-11-06 21:12:44 -0800
commitcc8eeeb482f279c80ebef17fc5968e73a51b48b8 (patch)
treeab1ae00741148e617af41c57a285e74a6cd5d43d /examples/recursion.ts
parentccaff310c85a64a852d96ee71ecf9640de57ea36 (diff)
add examples
Diffstat (limited to 'examples/recursion.ts')
-rw-r--r--examples/recursion.ts18
1 files changed, 18 insertions, 0 deletions
diff --git a/examples/recursion.ts b/examples/recursion.ts
new file mode 100644
index 0000000..8ee899f
--- /dev/null
+++ b/examples/recursion.ts
@@ -0,0 +1,18 @@
+/*
+Any practical programming language can of course handle recursion, and KaiScript is no exception.
+Factorial is a function that is particularly easy to define recursively.
+*/
+
+import { createFn } from "../src";
+
+// bind(name, fn) returns fn inside a closure containing itself bound to name
+const factorial = createFn<[number]>()(
+ `bind(fac,fn(n,?(eq(n, 1),n,mul(n,call(fac,sub(n,1))))))`
+);
+
+// const factRes: 720
+const factRes = factorial(6);
+console.log(factRes);
+
+// You might be disappointed to learn that computing factorials larger than 6
+// fails catastrophically. Blame TypeScript.