From ebfd74ddf0ef6372624ea171e06f8460d0e1351b Mon Sep 17 00:00:00 2001 From: Cody Date: Mon, 27 Feb 2023 07:21:50 -0600 Subject: pain --- examples/fib.sloth | 27 ++++++++++++++++++--------- examples/fib_gen.sloth | 14 ++++++++++++++ examples/fib_rec.sloth | 7 +++++++ 3 files changed, 39 insertions(+), 9 deletions(-) create mode 100644 examples/fib_gen.sloth create mode 100644 examples/fib_rec.sloth (limited to 'examples') 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 { - 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 { + 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), + } +} -- cgit v1.2.3