Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
ANN: pattern guards
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jeremy Yallop <jeremy.yallop@e...>
Subject: ANN: pattern guards
I'm pleased to announce the initial release of `patterns', an OCaml
extension providing general-purposes additions to pattern matching.
This release includes a single feature: "pattern guards"; others will
be made available in the near future.

You can download patterns from

Pattern guards generalize "when"-guards to allow arbitrary pattern
matching with binding.  After each pattern in a match you can write
one or more binding phrases as follows:

   match e with
     | patt1 with p1 = e1
             with pn = en
          -> e
     | patt2 ...

The expressions e1 ... en are evaluated in turn and matched with
the corresponding patterns p1 ... pn until either a match fails (in
which case matching proceeds with patt2 etc.) or all matches
succeed.  Any variables bound in p1 ... pn are in scope within
subsequent guards and within e.

For example, given a function

    val lookup : 'a -> ('a * 'b) list -> 'b option

you might write the following

    let f env = function
     | Var x
          with Some v = lookup x env -> ... v ...

instead of the less elegant and less efficient

    let f env = function
     | Var x
          when mem_assoc x env -> ... assoc x env ...

Pattern guards and regular guards can be freely intermixed; for
example, you can write

   match e with
     | patt when c1
            with patt1 = e1
            when c2
            with patt2 = e2 -> e
     | ...

Pattern guards were proposed (for Haskell) in

    Martin Erwig and Simon Peyton Jones
    Pattern Guards and Transformational Patterns
    Haskell Workshop, 2000

See also: