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

前端 未结 4 1108
闹比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条回答
  •  一个人的身影
    2020-12-02 08:13

    A very related example run through can be found here, although I haven't gone over it completely it maybe of some help.

    I am not exactly sure of the implementation details, but I suspect they should be on the lines of my argument below.

    Please take this with a pinch of salt, this maybe inaccurate implementationally but just as an understanding aid.

    Haskell will not evaluate anything unless it is forced to, that is known as Lazy Evaluation, which is a beautiful concept in itself.

    So lets assume we've been asked only to do a take 3 fibs Haskell stores the fibs list as 0:1:another_list, since we've been asked to take 3 we may as well assume it is stored as fibs = 0:1:x:another_list and (tail fibs) = 1:x:another_list and 0 : 1 : zipWith (+) fibs (tail fibs) will then be 0 : 1 : (0+1) : (1+x) : (x+head another_list) ...

    By pattern matching Haskell knows that x = 0 + 1 So leading us to 0:1:1.

    I'll be really interested though if someone knows some proper implementational details. I can understand that Lazy Evaluation techniques can be fairly complicated though.

    Hope this helps in understanding.

    Mandatory disclaimer again : Please take this with a pinch of salt, this maybe inaccurate implementationally but just as an understanding aid.

提交回复
热议问题