Haskell惰性评估和重用 [英] Haskell Lazy Evaluation and Reuse

查看:98
本文介绍了Haskell惰性评估和重用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,如果我要计算Haskell中的正方形列表,我可以这样做:

I know that if I were to compute a list of squares in Haskell, I could do this:

squares = [ x ** 2 | x <- [1 ..] ]

然后当我像这样调用方块时:

Then when I call squares like this:

print $ take 4 squares

它会打印出[1.0,4.0,9.0,16.0]。这被评估为[1 ** 2,2 ** 2,3 ** 2,4 ** 2]。既然Haskell是功能性的,并且结果每次都是相同的,如果我在其他地方再次调用方块,它是否会重新评估它已经计算出来的答案?如果我已经调用上一行后重新使用方块,它是否会重新计算前4个值?

And it would print out [1.0, 4.0, 9.0, 16.0]. This gets evaluated as [ 1 ** 2, 2 ** 2, 3 ** 2, 4 ** 2 ]. Now since Haskell is functional and the result would be the same each time, if I were to call squares again somewhere else, would it re-evaluate the answers it's already computed? If I were to re-use squares after I had already called the previous line, would it re-calculate the first 4 values?

print $ take 5 squares

它会评估[1.0,4.0,9.0,16.0,5 ** 2]?

Would it evaluate [1.0, 4.0, 9.0, 16.0, 5 ** 2]?

推荐答案

在这种情况下,它不会被重新计算,因为列表实际上已经建立,并且正方形列表继续在通话后存在。但是,通常Haskell函数不会被记忆。这只适用于这种情况,你没有明确地调用函数,只是探索一个(in)有限的列表。

In this case, it won't be recalculated because the list actually gets built, and the squares list continues to exist after the call. However, Haskell functions in general are not memoized. This only works for a case like this where you're not explicitly calling a function, just exploring an (in)finite list.

这篇关于Haskell惰性评估和重用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆