当参数是列表时,惰性求值如何工作? [英] How does lazy evaluation works when the argument is a list?
问题描述
根据我的理解,惰性求值是在将参数传递给函数之前不对它们进行求值,而是仅在实际使用它们的值时才对它们求值.
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.
但是在haskell教程中,我看到了一个示例.
But in a haskell tutorial, I see an example.
xs = [1,2,3,4,5,6,7,8]
doubleMe(doubleMe(doubleMe(xs)))
作者说,命令式语言很可能会一次通过列表,然后复制并返回.然后它将再次通过列表两次,并返回结果.
The author said an imperative language would probably pass through the list once and make a copy and then return it. Then it would pass through the list another two times and return the result.
但是用一种懒惰的语言,它会先计算
But in a lazy language, it would first compute
doubleMe(doubleMe(doubleMe(1)))
这将返回一个doubleMe(1)
,即2
.然后是4
,最后是8
.
This will give back a doubleMe(1)
, which is 2
. Then 4
, and finally 8
.
因此,只有在您确实需要时,它才会通过列表.
So it only does one pass through the list and only when you really need it.
这让我感到困惑.为什么懒惰的语言不将列表作为一个整体,而是将其拆分?我的意思是我们可以在使用列表或表达式之前忽略它.但是使用时我们需要评估整个过程,不是吗?
This makes me confused. Why don't lazy language take the list as a whole, but split it? I mean we can ignore what the list or the expression is before we use it. But we need to evaluate the whole thing when we use it, isn't it?
推荐答案
像[1,2,3,4,5,6,7,8]
这样的列表只是用于此目的的语法糖:1:2:3:4:5:6:7:8:[]
.
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:[]
所有Haskell列表都是链接列表,这意味着它们具有 head 和 tail .在上面的示例中,头是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:[]
在这里,h
指的是1
.如果只需要h
,则没有理由评估列表的其余部分(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.
这就是对列表进行惰性计算的方式.在需要该值之前,1+1
仍然是 thunk (未计算的表达式).
That's how lists are lazily evaluated. 1+1
remains a thunk (an unevaluated expression) until the value is required.
这篇关于当参数是列表时,惰性求值如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!