[Haskell-cafe] Short circuiting and the Maybe monad
graham.fawcett at gmail.com
Thu May 15 09:27:38 EDT 2008
On Wed, May 14, 2008 at 1:38 AM, Janis Voigtlaender
<voigt at tcs.inf.tu-dresden.de> wrote:
> 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.
I didn't mean to suggest that. I confess to using 'the f >>= g >>= h
thunks' as a shorthand for the thunks for f, g and h, and not for the
binding expressions. I did write later in my message that there would
be evaluation overhead, but that I suspected it would be negligible
(an imprecise and hand-waving statement, to be sure).
> 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
Neat, I've never seen a bind operator used in a pattern. Thanks for
>> talk s = Just' . (trace s)
>> f = talk "--f"
>> g = talk "--g"
>> h = talk "--h"
>> foo n = n >>= f >>= g >>= h
> *Main> foo Nothing'
> So you get three pattern-matches on Nothing', where with the associative
>> foo' n = n >>= \a -> f a >>= \b -> g b >>= h
> you get only one:
> *Main> foo' Nothing'
> For a way to obtain such improvements automatically, and without
> touching the code, you may want to look into
Much appreciated, Janis, I look forward to reading the paper.
> Ciao, Janis.
> Dr. Janis Voigtlaender
> mailto:voigt at tcs.inf.tu-dresden.de
More information about the Haskell-Cafe