aboutsummaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rw-r--r--examples/fib.sloth27
-rw-r--r--examples/fib_gen.sloth14
-rw-r--r--examples/fib_rec.sloth7
3 files changed, 39 insertions, 9 deletions
diff --git a/examples/fib.sloth b/examples/fib.sloth
index 415de05..e98764a 100644
--- a/examples/fib.sloth
+++ b/examples/fib.sloth
@@ -1,15 +1,24 @@
-## Calculate a specific number in the fibonacci sequence
fn fib(n: i32) -> i32 {
- match n {
- 0 | 1 => n,
- _ => fib(n - 1) + fib(n - 2),
+ if n == 0 || n == 1 {
+ return n;
}
-}
-generator fn fib_sequence(range: Range<i32>) -> i32 {
- for n in range {
- yield fib(n);
+ var grandparent = 0;
+ var parent = 1;
+ var me = 0;
+
+ for i in 0..n-1 {
+ me = parent + grandparent;
+ grandparent = parent;
+ parent = me;
}
+
+ return me;
}
-print(fib_sequence(0..20).join(", "))
+print fib(0);
+print fib(1);
+print fib(2);
+print fib(3);
+print fib(4);
+print fib(5);
diff --git a/examples/fib_gen.sloth b/examples/fib_gen.sloth
new file mode 100644
index 0000000..dd9e08f
--- /dev/null
+++ b/examples/fib_gen.sloth
@@ -0,0 +1,14 @@
+fn fib(n: i32) -> i32 {
+ match n {
+ 0 | 1 => n,
+ _ => fib(n - 1) + fib(n - 2),
+ }
+}
+
+generator fn fib_sequence(range: Range<i32>) -> i32 {
+ for n in range {
+ yield fib(n);
+ }
+}
+
+print(fib_sequence(0..20).join(", "))
diff --git a/examples/fib_rec.sloth b/examples/fib_rec.sloth
new file mode 100644
index 0000000..306bcdf
--- /dev/null
+++ b/examples/fib_rec.sloth
@@ -0,0 +1,7 @@
+## Calculate a specific number in the fibonacci sequence
+fn fib(n: i32) -> i32 {
+ match n {
+ 0 | 1 => n,
+ _ => fib(n - 1) + fib(n - 2),
+ }
+}