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 evaluated 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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With