Performance of lazy evaluation in Haskell when the arguments appear several times
Let's say I have a function which can calculate power of four of a number defined by
let power4 x = x*x*x*x
And I try to pass x = (3 + 8)*2
let result = power4 ((3 + 8)*2)
Since in Haskell, the values are evaluat开发者_运维问答ed until they are needed, does it mean that x will evaluate four times? If so, is there any way to improve the Haskell compiler?
Thanks.
No, it will only be evaluated once. In call by name it would be evaluated four times, but all Haskell implementations are call by need (although the standard does not require this), which means each expression will be evaluated at most once.
This only applies when the expression is fully concrete. E.g. there is no guarantee that in:
foo x = x + (1+2)
bar = foo 3 + foo 4
That when computing bar
, (1+2)
will be evaluated only once. In fact, it will probably be evaluated twice (if compiled without optimizations).
If you aren't sure, you could use trace
to check (ref: http://www.haskell.org/haskellwiki/Debugging):
import Debug.Trace
power4 x = x*x*x*x
main = print $ power4 (trace "called" ((3+8)*2))
result:
called
234256
so the expression is only evaluated once.
精彩评论