Understanding a recursively defined list (fibs in terms of zipWith)

前端 未结 4 1097
闹比i
闹比i 2020-12-02 07:40

I\'m learning Haskell, and came across the following code:

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

which I\'m having a bit of trouble p

4条回答
  •  Happy的楠姐
    2020-12-02 08:13

    Let's take a look at definition of zipWith zipWith f (x:xs) (y:ys) = f x y : zipWith xs ys

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

    For take 3 fibs substituting the definition of zipWith and xs = tail (x:xs) we get 0 : 1 : (0+1) : zipWith (+) (tail fibs) (tail (tail fibs))

    For take 4 fibs substituting once more we get 0 : 1 : 1 : (1+1) : zipWith (+) (tail (tail fibs)) (tail (tail (tail fibs)))

    and so on.

提交回复
热议问题