I think you just made a typo. Here's what your fibgen
function looks like reformatted:
(fn fibgen [a b]
(cons a (fibgen b (+ a b)))
0
1)
This function realizes the entire Fibonacci sequence starting with a
and b
, then returns 1. What you meant to do was define a function that returns the sequence, call it with 0 and 1, and then take the first ten items from that sequence:
(take 10 ((fn fibgen [a b] (cons a (fibgen b (+ a b)))) 0 1))
If you run this, you'll get an ArithmeticException
for integer overflow, because numbers in the Fibonacci sequence quickly leave the range of a 64-bit integer. You can fix this using +'
:
(take 10 ((fn fibgen [a b] (cons a (fibgen b (+' a b)))) 0 1))
Since Clojure isn't lazy, this will try to realize the entire Fibonacci sequence, which will cause a StackOverflowError
. Even though Clojure itself isn't lazy, though, you can create a lazy sequence, which will have basically the same effect in this case:
(take 10 ((fn fibgen [a b] (lazy-seq (cons a (fibgen b (+' a b))))) 0 1))
;;=> (0 1 1 2 3 5 8 13 21 34)