[Haskell-cafe] Short circuiting and the Maybe monad

Graham Fawcett graham.fawcett at gmail.com
Tue May 13 11:23:35 EDT 2008


On Mon, May 12, 2008 at 6:09 PM, John Hamilton <jlhamilton at gmail.com> wrote:
> I'm trying to understand how short circuiting works with the Maybe monad.
>  Take the expression n >>= f >>= g >>= h, which can be written as
>  (((n >>= f) >>= g) >>= h) because >>= is left associative.  If n is
>  Nothing, this implies that (n >>= f) is Nothing, and so on, each nested
>  sub-expression easily evaluating to Nothing, but without there being a
>  quick way to short circuit at the beginning.

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:

  > import Debug.Trace

  > talk s = Just . (trace s)
  > f = talk "--f"
  > g = talk "--g"
  > h = talk "--h"

  > foo n = n >>= f >>= g >>= h

  *Main> foo (Just 3)
  Just --h
  --g
  --f
  3
  *Main> foo Nothing
  Nothing

I suspect the cost of creating and discarding those unused thunks is
negligible, so in effect the associativity of the bind operator is
irrelevant here.

Graham


More information about the Haskell-Cafe mailing list