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

ⅰ亾dé卋堺 提交于 2019-12-02 01:11:56

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!