For reference, here is the description of Project Euler Problem #2.
The code I came up to generate Fibonacci numbers turned out to be exactly the same as found in “Programming Clojure” by Stuart Halloway, so I guess the idiom using
iterate was still lurking in my brain after reading it.
(def fibo (map first (iterate (fn [[a b]] [b (+ a b)]) [0 1]))) (reduce + (filter even? (take-while #(> 4000000 %) fibo)))
Among the other solutions that people had posted, I liked the (sort of Haskel-esque?) answer by achim_p. Using
lazy-cat were interesting choices. I repost his code here:
(def fibs (lazy-cat '(0 1) (map + fibs (drop 1 fibs)))) (reduce + (take-while (partial >= 4000000) (filter even? fibs)))
In this case, using
(partial > 4000000) doesn’t really seem to be any shorter or clearer than an anonymous functions like
#(> 4000000 %). I wonder which is better style?
As for performance, both the
lazy-cat idioms for making lazy sequences seem to be roughly equivalent….blazing fast!