The Haskell code in question:
fibs = 1:1:zipWith (+) fibs (tail fibs)
It's also a common showcase for Perl6 lazy lists: my @fibs = 1, 1, * + * ... *;Note that Perl6 uses big integers by default, so this will work even beyond the limit n=92 at which 64-bit integers will overflow.
Re:Once you go functional, you can never go back
by dllthomas on Monday May 18, 2015 @08:23PM
(#9567577)
Haskell does this, too.
Re:Once you go functional, you can never go back
by codygman on Tuesday May 19, 2015 @04:46AM
(#9568746)
I will admit perl 6 is pretty damn cool. I'll definitely have to look at it soon.
Re:Once you go functional, you can never go back
by nanny on Monday May 18, 2015 @09:38AM
(#9564308)
Seriously: Scheme is guaranteed to have tail-call replacement, the author should really take advantage of that.
Here's one that does:
(define (fib-tco n)
(let loop ((x 0)
(y 1)
(num n))
(if (zero? n)
x
(loop y (+ x y) (- num 1)))))
Try getting the 1000th Fibonacci number which each of these.Also, what's with the dangling parentheses?
Re:Once you go functional, you can never go back
by cousin_it on Monday May 18, 2015 @09:25AM
(#9564254)
Here's a page about calculating Fibonacci numbers efficiently:
http://www.nayuki.io/page/fast-fibonacci-algorithms
The method you linked to is listed there as "Dynamic programming (slow)".
Re:Once you go functional, you can never go back
by philh on Monday May 18, 2015 @09:40AM
(#9564323)
> Actually calculating the Fibonacci series efficiently in a non-lazy functional language looks surprisingly non-trivial.
I don't know if you'd count it as trivial, but one could do
def fib(n, a=0, b=1, c=2):
if n <= 1:
return n
if n == c:
return a+b
return fib(n, b, a+b, c+1)
which beats the Haskell lazy list in being O(1) space (except Python doesn't eliminate tail calls).
Re:Once you go functional, you can never go back
by wz1000 on Monday May 18, 2015 @10:07AM
(#9564473)
The front of the list can be garbage collected, so the Haskell version can be O(1) in memory.
Actually calculating the Fibonacci series efficiently in a non-lazy functional language looks surprisingly non-trivial. In Haskell it's pretty simple:
http://blog.srinivasan.biz/software/fibonacci-numbers-the-sl...