-2

I'm a complete beginner with Haskell and just encountered the following terse expression for constructing the Fibonacci sequence:

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

I think I understand what each individual piece is doing (:, zipWith, tail), and I know some sort of recursion is happening, but am not quite sure how.

dsaxton
  • 913
  • 1
  • 8
  • 21

1 Answers1

1

The first two values are 0 and 1. Thereafter, the elements are appended (zipped on) by adding the current and immediately previous series, shifted by one position.

For instance, if the "current" list is (0, 1, 1, 2, 3, 5), then the tail is (1, 1, 2, 3, 5). Adding these gives us ...

fibs = (0, 1, 1, 2, 3, 5)
tail = (1, 1, 2, 3, 5)
sum  = (1, 2, 3, 5, 8)

This gives us the expression

0: 1: (1, 2, 3, 5, 8)

... which results in a one-element extension of the list. When we recur on this without limit, we get the Fibonacci sequence.

Prune
  • 72,213
  • 14
  • 48
  • 72
  • I'm more interested in how the recursion works, but that's explained in the answer to the linked question. – dsaxton Sep 15 '16 at 17:34