Допис з розмови
Avoid unnecessary evaluations
Path: g2news2.google.com!news1.google.com!news.glorb.com!feeder.erje.net!news.musoftware.de!wum.musoftware.de!fu-berlin.de!uni-berlin.de!news.dfncis.de!not-for-mail
From: Frank Poettgen <Frank.Poett...@Post.RxWyTxH-AyAzCyHzEyN.de>
Newsgroups: comp.lang.haskell
Subject: Re: Avoid unnecessary evaluations
Date: Thu, 28 May 2009 17:01:17 +0200
Lines: 28
Message-ID: <787n9qF1ktudiU1@mid.dfncis.de>
References: <787ia8F1h6d4hU1@mid.dfncis.de> <4a1e9b9e$1_2@news.arcor-ip.de>
Mime-Version: 1.0
Content-Type: text/plain; charset=ISO-8859-15; format=flowed
Content-Transfer-Encoding: 7bit
X-Trace: news.dfncis.de WRtFfatqSyreTJG9WqARFQV++pcof32yuEe65x8V0+ngJlcIovH9UG07yz
Cancel-Lock: sha1:70oo8Ns6BZuFSk2tFj3yXpIC8kk=
User-Agent: Thunderbird 2.0.0.18 (Windows/20081105)
In-Reply-To: <4a1e9b9e$1_2@news.arcor-ip.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!