Can anyone explain this lazy Fibonacci decision?

This is the code:

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

When evaluated, it fibsis an endless list of Fibonacci numbers. What I don't understand is how the list is combined.

zipWithreturns a list, so zipping fibswill matter:

0 : 1 : [1] : [1,2] : [1,2,3]

Because it 0 : 1 : zipWith (+) [0,1] [1]gives [1]and zipWith (+) [0,1,1] [1,1]gives [1,2], etc.).

However, when I run the code, I get the correct result.

What I don’t understand here?

+4
source share
1 answer

" " . " " , , . , , .

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

? . , . .

? : " [] x : xs?" , .

fibs, ,

fibs = x0 : xs0
x0  = 0
xs0 = 1 : zipWith (+) fibs (drop 1 fibs)

( fibs, x0)

xs0 = 1 : zipWith (+) (0 : xs0) (drop 1 (0 : xs0))

, ​​,

xs0 = x1 : xs1
x1  = 1
xs1 = zipWith (+) (0 : xs0) (drop 1 (0 : xs0))

xs1 = zipWith (+) (0 : 1 : xs1) (drop 1 (0 : 1 : xs1))

, - . , , ? xs1, zipWith, drop.

xs1 = zipWith (+) (0 : 1 : xs1) (drop 1 (0 : 1 : xs1))
    = zipWith (+) (0 : 1 : xs1) (1 : xs1)
    = (0 + 1) : zipWith (+) (1 : xs1) xs1

xs1 = x2 : xs2
x2  = 0 + 1 = 1
xs2 = zipWith (+) (1 : xs1) xs1
    = zipWith (+) (1 : 1 : xs2) (1 : xs2)

? , zip- . , "". xs2,

xs2 = zipWith (+) (1 : 1 : xs2) (1 : xs2)
    = (1 + 1) : zipWith (1 : xs2) xs2
xs2 = x3 : xs3
x3  = 1 + 1 = 2
xs3 = zipWith (1 : xs2) xs2
    = zipWith (1 : 2 : xs3) (2 : xs3)

!

, , zipWith, , , .

, , . , , , , . ( - , .)

, " " , , . , .

+10

Source: https://habr.com/ru/post/1610201/


All Articles