| |
comp.lang.haskell |
>> Will 'expensive x' be evaluated twice to compute 'f x'? > That will depend on your compiler. Some compilers do common >> If so, how can I avoid it? > Rewrite the function by hand: > f x = fst e + snd e where e = expensive > or, using pattern matching, > f x = l + r where (l, r) = expensive x > or, more compact but less comprehensible, > f = uncurry (+) . expensive
>> f :: Int -> Int
>> f x = fst (expensive x) + snd (expensive x)
> subexpression elimination, others don't. The reason is that
> this transformation can sometimes introduce space leaks. In
> your case it wouldn't be dangerous, but you cannot rely on
> your compiler recognizing this.