[Haskell-cafe] Short circuiting and the Maybe monad
Janis Voigtlaender
voigt at tcs.inf.tu-dresden.de
Wed May 14 01:38:56 EDT 2008
Graham Fawcett wrote:
> Yes, but that's still a 'quick' short-circuiting. In your example, if
> 'n' is Nothing, then the 'f >>= g >>= h' thunks will not be forced
> (thanks to lazy evaluation), regardless of associativity. Tracing
> verifies this:
No, it doesn't. What your tracing verifies is that the f, g, and h will
not be evaluated. It doesn't verify that the 'f >>= g >>= h' part of the
expression causes no evaluation overhead. Because that is not true.
Consider the following:
> import Debug.Trace
> data Maybe' a = Nothing' | Just' a deriving Show
> instance Monad Maybe' where
> return = Just'
> Nothing' >>= _ = trace "match" Nothing'
> Just' a >>= k = k a
> talk s = Just' . (trace s)
> f = talk "--f"
> g = talk "--g"
> h = talk "--h"
> foo n = n >>= f >>= g >>= h
Now:
*Main> foo Nothing'
match
match
match
Nothing'
So you get three pattern-matches on Nothing', where with the associative
variant
> foo' n = n >>= \a -> f a >>= \b -> g b >>= h
you get only one:
*Main> foo' Nothing'
match
Nothing'
For a way to obtain such improvements automatically, and without
touching the code, you may want to look into
http://wwwtcs.inf.tu-dresden.de/~voigt/mpc08.pdf
Ciao, Janis.
--
Dr. Janis Voigtlaender
http://wwwtcs.inf.tu-dresden.de/~voigt/
mailto:voigt at tcs.inf.tu-dresden.de
More information about the Haskell-Cafe
mailing list