[Haskell-beginners] Where/Let clauses and subexpression repetition/memoization

Daniel Fischer daniel.is.fischer at googlemail.com
Fri Aug 19 11:52:09 CEST 2011


On Friday 19 August 2011, 04:22:22, Brandon Allbery wrote:
> On Thu, Aug 18, 2011 at 21:21, Michael Serra <mk.serra at gmail.com> wrote:
> > My "superstition" here has been that the former only evaluates pxls'
> > once, whereas the latter computes it twice.  This seems like a basic
> > issue which must have been confirmed or debunked somewhere in my
> > readings, but it hasn't sunk in with me.
> 
> As I understand it, common subexpression elimination in lazy languages
> is difficult at best because the shared subexpressions may thereby
> become ineligible for fusion, so you're expected to do it explicitly by
> means of where/let clauses.  So your superstition is actually the
> truth.

With a small grain of salt or two.

The language allows both, sharing and recomputation, in both cases.
But an implementation that did not share if the value is bound to a name in 
a where/let would grossly violate the users' expectations, so per principle 
of least surprise you can pretty much rely on sharing in the first case.

The latter is harder to predict. In most cases, you'll get recomputation, 
but GHC does a bit of CSE, so in some cases it will compute only once and 
share the result (which may be a bad thing - that's a further reason for 
not doing too much CSE, sometimes sharing has catastrophic results).



More information about the Beginners mailing list