Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.



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.


That's fantastic!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: