Перейти до Домашньої сторінки Груп Google    comp.lang.haskell
Re: Avoid unnecessary evaluations

Frank Poettgen <frank.poett...@post.rxwytxh-ayazcyhzeyn.de>

Florian Kreidler wrote:
>> f :: Int -> Int
>> f     x  = fst (expensive x) + snd (expensive x)

>> Will 'expensive x' be evaluated twice to compute 'f x'?

> That will depend on your compiler. Some compilers do common
> 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.

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

Thanks a lot!