1

I'm new to Haskell, and was wondering what the difference between these two functions are.

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

 fib1 = 1 :1 : [a+b | (a,b) <- zip fib1 (tail fib1)]

I would like to know how they are working more clearly.

How I currently understand them is as follows:

I know that zipWith in the first function will apply the addition function to two lists in this case "fibs" and "tail fibs". However I'm confused on how the recursion is working. I know fibs returns a list and tail fibs would be everything except the head of the list. However I guess I'm confused on the intermediate steps and how zipWith is working with this recursively.

In fib1 I have the same question as above for "zip" but also how exactly is this getting applied to "a" and "b". Also why are "a" and "b" in a tuple?

I'm sorry if I haven't been more clear. I appreciate any help people could offer

Thanks in advance

agarc
  • 61
  • 6
  • With respect to `fib1`: `zip` is the same as `zipWith (,)` (or, more verbosely, `zipWith (\a b -> (a, b))`. – duplode Apr 23 '17 at 18:10

1 Answers1

1

In the first function, what you have is an infinity recursion that create the Fibonacci series in a list. The tail is used to refer to the next element in the sequence, for adding those two together. I think that by tracing the creation of the third element you'll understand better what is happening:

zipWith (+) fibs (tail fibs) ->
zipWith (+) (0 : 1 : zipWith (+) fibs (tail fibs)) (1 : zipWith (+) fibs (tail fibs)) ->
(0 + 1 : 1 + zipWith (+) fibs (tail fibs) : ...)

You can see that each element in the fibs list is created by adding its two former numbers in the sequence.

In fib1 something similar is happening. You are grouping in a tuple two adjacent numbers in the sequence and then declaring that the list is the sum of those two tuples (you can "solve" it like I did above to better understand what is happening). Note that the tuple itself is not important, just a way to pass data around. You can have the same effect with a list or a user-defined type.

Please tell me if something is not clear. Cheers

Yotam Ohad
  • 322
  • 3
  • 12