【发布时间】:2015-03-31 10:01:52
【问题描述】:
我需要澄清一下 Haskell 的懒惰。
如果我有这个功能:
myFunction arg
| arg == 1 = a
| arg == 2 = a*b
| arg == 3 = b+c
| otherwise = (a+b)*c
where
a = ...
b = ...
c = ...
d = ...
当我调用myFunction 1 时,Haskell 将只评估 a = ... 函数,既不评估 b 也不评估 c 也不评估 d。
但是如果我写
myFunction arg
| arg == 1 = a
| arg == 2 = a*b
| arg == 3 = b+c
| otherwise = (a+b)*c
where
(a,b,c,d) = anotherFunction arg
Haskell 的行为会是什么?
- 它会仅评估 a 并将惰性“传播”到
anotherFunction吗? - 或者,它会评估整个元组 (a,b,c,d) 作为
anotherFunction的结果吗?
【问题讨论】:
-
它将评估元组
x = anotherFunction arg,但不会评估元组的所有元素。 -
当您说“致电
myFunction 1”时,我假设您的意思是在评估该表达式时。正如 Zeta 所说,它将评估元组(但不是元素),然后从该元组评估a。 -
@Zeta 元组
b,c和d的其他值将是 thunk 形式。或者有更合适的词吗? -
@Sibi:我想说元组将是 weak head normal form 更合适,但是 thunk 是可以的。
-
@Zeta 谢谢,已适当更新。