Simpler Fibonacci function

Jeffrey R Lewis jeff@galois.com
Tue, 5 Feb 2002 11:16:54 -0800


On Tuesday 05 February 2002 09:40 am, Brian Berns wrote:
> I am new to functional programming and teaching myself Haskell.  The
> canonical Haskell "fib" function (e.g. as presented in the "Gentle"
> tutorial) is:
>
>    fib = 1 : 1 : [ a+b | (a,b) <- zip fib (tail fib) ]
>
> This seems, to be polite, a bit overly complex.  By comparison, here
> is a simpler version:

As an aside, here's a nicer way of writing the stream version of fib:

    fib = 1 : 1 : [ a + b | a <- fib | b <- tail fib ]

This gets rid of the distraction of the zip and the pair, letting you see 
the simple structure of the definition more clearly.

This, however, is not Haskell 98 (the use of multiple generators separated 
by `|').  But it is supported by both GHC and Hugs (using flag -98).  See 
the sections in the user manuals under `parallel list comprehensions'.

--Jeff