aboutsummaryrefslogtreecommitdiff
path: root/examples/fastfib.sil
diff options
context:
space:
mode:
authorCamil Staps2017-07-28 12:34:04 +0200
committerCamil Staps2017-07-28 12:37:18 +0200
commit6c16995cdd8d8c9d76de2cbe8031634141766c80 (patch)
treee8d027eee781267f7de1a5087d6bda46512040fe /examples/fastfib.sil
parentUpdate grammar (diff)
Add a semi-memoized fibonacci with lists
Diffstat (limited to 'examples/fastfib.sil')
-rw-r--r--examples/fastfib.sil35
1 files changed, 35 insertions, 0 deletions
diff --git a/examples/fastfib.sil b/examples/fastfib.sil
new file mode 100644
index 0000000..0c28ccd
--- /dev/null
+++ b/examples/fastfib.sil
@@ -0,0 +1,35 @@
+Int length([Int] xs) {
+ if (xs.nil) {
+ return 0;
+ } else {
+ return 1 + length(xs.tl);
+ }
+}
+
+Int get([Int] xs, Int i) {
+ if (i == 0) {
+ return xs.hd;
+ } else {
+ return get(xs.tl, i-1);
+ }
+}
+
+// This is not really memoized, as this could be emulated by keeping the last
+// two entries in memory. However, real memoization would only make sense with
+// an array and sil does not have arrays (yet).
+Int fib(Int n) {
+ [Int] fibs;
+ fibs := [1,1];
+ n := n - 2;
+
+ while (!(n == 0)) {
+ fibs := get(fibs,0) + get(fibs,1) : fibs;
+ n := n - 1;
+ }
+
+ return fibs.hd;
+}
+
+Int main() {
+ return fib(92); // Largest to fit in a 64-bit integer
+}