Is it possible to implement the fibonacci series in Clojure efficiently using reduce
? What would the "accumulator" contain?
I imagine that it will have to be lazy. It's obvious how to do it using recursion or loop/recur.
Is it possible to implement the fibonacci series in Clojure efficiently using reduce
? What would the "accumulator" contain?
I imagine that it will have to be lazy. It's obvious how to do it using recursion or loop/recur.
You could use a pair of successive fibonacci values as the accumulator, as follows:
This is not particularly efficient due to the creation of lots of intermediate pairs and use of the superfluous range sequence to drive the right number of iterations, but it is O(n) from an algorithmic perspective (i.e. the same as the efficient iterative solution, and much better than the naive recursive one).
Not using map/reduce, but iterate can avoid recursion too.
This takes 21ms on an Intel 2.4 Ghz
On the same machine, reduce takes 61msec. Not sure why iterate is faster.