Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 653
DB Tsai Avatar asked Oct 11 '11 04:10

DB Tsai


Video Answer


1 Answers

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).

like image 172
luqui Avatar answered Oct 29 '22 02:10

luqui