[Haskell-beginners] Re: Understanding cached fibonnacci function

Daniel Fischer daniel.is.fischer at web.de
Fri Jan 30 10:24:07 EST 2009


Am Freitag, 30. Januar 2009 15:59 schrieb Ertugrul Soeylemez:
> Daniel Fischer <daniel.is.fischer at web.de> wrote:
> > Not to forget the marvellous
> >
> > import Control.Monad.Fix
> >
> > fibs :: [Integer]
> > fibs = fix ((0:) . scanl (+) 1)
>
> I don't like that one.  My favorite is the following, because it's
> short, concise and still very comprehensible:
>
>   import Data.Function
>
>   fibs :: Num i => [i]
>   fibs = fix (\r x y -> x : r y (x+y)) 0 1

But that's too easy to understand!
What a waste of fix, sheesh ;-)

My favourite is

fibs = 0:1:zipWith (+) fibs (tail fibs)

clear, elegant, accessible.  But I also like the other one, precisely because, 
unless one is very experienced, one has to do a few rounds of "Wait, how on 
earth does this work?" before it clicks.

>
> Replace 0 by 1, if you want to exclude it from the sequence.  I prefer
> to include it.

Yep. Much more natural if the powers match the index.
>
>
> Greets,
> Ertugrul.

Cheers,
Daniel


More information about the Beginners mailing list