Lurker News

Comments (491) 209 threads

Show all comments

Showing thread 55 of 209

squirrelicus1 reply#
I'm by no means a Haskell evangelist, but I believe it's a great educational tool for devs.

You've made a Fibonacci number algorithm. Recursive it's slow, iterative it's nasty. There's another way
> let fib = 0 : 1 : zipWith (+) fib (tail fib)
Then to get the 10kth Fibonacci number you can
> fib !! 10000
It's fast. It's tiny. It has no risk of stack overflow because it's not a recursive function. It illustrates how and why lazy evaluation is important and even better than eager evaluation in many cases. I use this principle in my C#/Java work a lot.
It's my favorite.

tromp1 reply#
Or the even more succinct

    fibs = 0 : scanl (+) 1 fibs
scanl is similar to a fold, but returns a list of successive reduced values from the left.
squirrelicus#
That's fantastic!