Understanding Haskell's fibonacci

Solution 1:

Due to the upvotes I made my comment into an answer.

What you see is not a guard but it is list comprehension. For starters think of it as a way to express a mathematical set notation like A = { x | x element N } which means something along the lines of: The set A is the set of all natural numbers. In list comprehension that would be [x | x <- [1..] ].

You can also use constraints on your numbers: [x | x <- [1..], x `mod` 2 == 0 ] and many other things.

There are alot of good haskell turorials out there that cover list comprehension and even a StackOverflow question regarding haskell resources.

Solution 2:

The only tricky thing is the zip fibs (tail fibs). zip just makes a pairwise list from each of its arguments. So if you have two lists like this:

[ 1, 2, 3, 4 ]
[ "a", "b", "c", "d" ]

Zipping them will make:

[ (1,"a"), (2,"b"), (3,"c"), (4,"d") ]

The left arrow (assignment into a destructuring pattern) just extracts the paired elements so they can be added together. The two lists being zipped are fibs and (tail fibs) -- in other words, the Fibonacci sequence, and the Fibonacci sequence offset by 1 element. Haskell is lazily-evaluated, so it can calculate the list to however many elements are required. This applies to zip as well.