[Haskell-beginners] scanl and infinite sequences [scanl for Fibonacci sequences]

Seung Soo, Ha sungsuha at gmail.com
Tue Jan 25 02:57:25 CET 2011


I was playing with the project Euler problems and found heaps of
Fibonacci generating codes in Haskell.
One caught my eye:

fib = 1 : scanl (+) 1 fib   ....(1)

when my understanding was limited to 
"folds just replace : with the function you provide
scans show all the intermediate states of your fold"
this line of code was very easy to understand.
Efficient too(according to the wiki article on Haskell)

But now that I'm trying to grasp foldl and foldr, I no longer understand that
line of code!!!

This is especially confusing, as afaik,  (1) is generating an infinite list but 
I thought you can't use foldl for infinite lists!
Tried replacing scanl with scanr 
(foldr is supposed to work with infinite lists right?)

fib = 1 : scanr (+) 1 fib .....(2)

somewhat surprisingly, (2) crashes.

I've read numerous articles on folds on the haskell wiki, and also this
stack overflow post (http://stackoverflow.com/questions/3082324)
Just as I thought I was getting a hold on the concept of folds... This..

What am I missing here?




More information about the Beginners mailing list