[Haskell] Repeated evaluation of a constant value.

Sven Moritz Hallberg sm at khjk.org
Mon Sep 25 16:13:20 EDT 2006


Lemmih <lemmih at gmail.com>, 2006-09-25 21.20 +0200:
> > > table :: [(String, Integer)] -> String -> Maybe Integer
> > > table ls str = Map.lookup str fm
> > >    where fm = trace "Trace: making the map" $ Map.fromList ls
> 
> to:
> 
> > > table :: [(String, Integer)] -> String -> Maybe Integer
> > > table ls = \str -> Map.lookup str fm
> > >    where fm = trace "Trace: making the map" $ Map.fromList ls

The point here is that in your original version, the 'where' refers to
the wrong closure, i.e. 'fm' doesn't live in the closure of 'table ls'
but 'table ls str'! So it is only created once the string is applied,
and thus again and again for every string. It's easier to see
if you convert the original to a lambda expression,

    table = \ls -> \str -> lookup str fm
      where fm = fromList ls

and turn the 'where' into a let:

    table = \ls -> \str -> let fm = fromList ls in lookup str fm


Hope this helps.

Sven Moritz


More information about the Haskell mailing list