3 ms·
> At the same time, [recursive fib] is slow as hell, because recalculates the very same value multiple times... That depends on the language and choice of eval
by nybble41 9y ago
> At the same time, [recursive fib] is slow as hell, because recalculates the very same value multiple times...
That depends on the language and choice of evaluation strategy. For example, in Haskell this recursive form is both elegant and fast:
fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
- dozzie 9y agoThere is this curious divergence between what people writing in Haskell consider elegant and what virtually everybody else considers elegant. I can't make heads or tails of your example, even though I'm versed enough in functional and imperative programming and I know what the code should do. But yes, in languages that cache the call results by default the original formula will be fast.
- nybble41 9y agoApart from non-strict evaluation, the example doesn't use any primitives which are not extremely common in any functional programming language: -- list constructor 1 : 2 : 3 : [] == [1,2,3] -- remove first item from a list tail [1,2,3] == [2,3] -- combine two lists "pointwise" zipWith (+) [1,2] [3,4] == [1+3,2+4] If you line up the Fibonacci numbers starting from the first element and the Fibonacci numbers starting from the second element, and add the corresponding elements, you get the remaining elements of the Fibonacci sequence. Visually: 1, 1, (2, 3, 5, 8, 13, ...) -- fibs 1, (2, 3, 5, 8, 13, ...) -- tail fibs + ========================== (2, 3, 5, 8, 13, ...) -- zipWith (+) This declaration: fibs = 1 : 1 : zipWith (+) fibs (tail fibs) is merely the previous recurrence diagram translated into code. That is why I consider it an elegant definition.