How does lazy evaluation works when the argument is a list?

后端 未结 1 1987
日久生厌
日久生厌 2021-01-22 10:07

From my understanding, lazy evaluation is the arguments are not evaluated before they are passed to a function, but only when their values are actually used.

But in a h

相关标签:
1条回答
  • 2021-01-22 10:19

    A list like [1,2,3,4,5,6,7,8] is just syntactic sugar for this: 1:2:3:4:5:6:7:8:[].

    In this case, all the values in the list are numeric constants, but we could define another, smaller list like this:

    1:1+1:[]
    

    All Haskell lists are linked lists, which means that they have a head and a tail. In the above example, the head is 1, and the tail is 1+1:[].

    If you only want the head of the list, there's no reason to evaluate the rest of the list:

    (h:_) = 1:1+1:[]
    

    Here, h refers to 1. There's no reason to evaluate the rest of the list (1+1:[]) if h is all you need.

    That's how lists are lazily evaluated. 1+1 remains a thunk (an unevaluated expression) until the value is required.

    0 讨论(0)
提交回复
热议问题