Pattern guards

David Roundy droundy at darcs.net
Thu Sep 28 20:31:37 EDT 2006


On Fri, Sep 29, 2006 at 02:59:49AM +0300, Yitzchak Gale wrote:
> Iavor Diatchki wrote:
> >I think that the benefit of adding pattern guards is... it provides
> >a concise notation
> 
> Not significantly more concise than existing notation.

That's just not true.  If all your pattern guards happen to involve
the Maybe monad, then perhaps you can rewrite the pattern guard code
almost as concisely using monadic notation, but it does mean that the
moment you choose to do that you have to completely give up on using
Haskell's existing pattern matching to define your function, unless
you happen to be defining a particularly simple function.

How do you nearly as concisely write a function such as this in
Haskell 98?

> foo (Left "bar") = "a"
> foo (Right x) | (b,"foo") <- break (==' ') x = "b " ++ b
> foo (Left x) | ("foo",c) <- break (==' ') x = "c " ++ c
> foo (Right x) | ["Hello",n,"how","are","you",d@(_:_)] <- words x,
                  last d == '?'
          = n ++ " is not here right now, but " ++ n ++ " is " ++
            init d ++ " fine."
> foo (Left x) | length x == 13 = "Unlucky!"
> foo (Right x) = x
> foo (Left x) = x

It's a contrived example, but the usefulness of pattern guards is only
greater on more realistic, more complicated functions.
-- 
David Roundy


More information about the Haskell-prime mailing list