为什么惰性求值有用? [英] Why is lazy evaluation useful?

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

问题描述

我一直想知道为什么惰性求值很有用.我还没有让任何人以一种有意义的方式向我解释;大多数情况下,它最终会归结为相信我".

I have long been wondering why lazy evaluation is useful. I have yet to have anyone explain to me in a way that makes sense; mostly it ends up boiling down to "trust me".

注意:我的意思不是记忆.

Note: I do not mean memoization.

推荐答案

主要是因为它可以更高效 -- 如果不使用值,则不需要计算它们.例如,我可能将三个值传递给一个函数,但根据条件表达式的顺序,实际上可能只使用一个子集.在像 C 这样的语言中,无论如何都会计算所有三个值;但在 Haskell 中,只计算必要的值.

Mostly because it can be more efficient -- values don't need to be computed if they're not going to be used. For example, I may pass three values into a function, but depending on the sequence of conditional expressions, only a subset may actually be used. In a language like C, all three values would be computed anyway; but in Haskell, only the necessary values are computed.

它还允许使用无限列表等很酷的东西.在像 C 这样的语言中我不能有一个无限列表,但在 Haskell 中,这没问题.无限列表在数学的某些领域中经常使用,因此拥有操作它们的能力会很有用.

It also allows for cool stuff like infinite lists. I can't have an infinite list in a language like C, but in Haskell, that's no problem. Infinite lists are used fairly often in certain areas of mathematics, so it can be useful to have the ability to manipulate them.

这篇关于为什么惰性求值有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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