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

Florian Kreidler <m...@privacy.net>

Frank Poettgen <Frank.Poett...@Post.RxWyTxH-AyAzCyHzEyN.de> schrieb:

> Assume that the evaluation of a function 'expensive' takes a lot of
> time. Hence I want to avoid unnecessary evaluations of 'expensive'.

> expensive :: Int -> (Int,Int)
> expensive     x  =  (x,x)

> 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