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

ANN: patterns v0.4
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2008-06-24 (21:27) From: Nathaniel Gray Subject: Re: [Caml-list] ANN: patterns v0.4
```On Fri, Jun 20, 2008 at 9:26 AM, Richard Jones <rich@annexia.org> wrote:
>
> Can someone summarise active patterns for us?  The MSDN site
> containing the paper is down at the moment.

Sure.  Active patterns are a lot like Wadler's "views", and thus are
similar to the stuff in micmatch.  With active patterns you can invoke
functions (implicitly) within pattern matches and match the results,
which allows you to provide a "virtual" algebraic data structure for
any value you might want to match against.  Here's an example from the
paper (using F# syntax):

open LazyList
let (|Cons|Nil|) l = if nonempty(l) then Cons(hd(l),tl(l)) else Nil

let rec pairSum xs =
match xs with
| Cons (x, Cons (y,ys)) -> consl (x+y) (lazy (pairSum ys))
| Cons (x, Nil ()) -> consl x (lazy nil)
| Nil () -> nil

This expands to:
let rec pairSum xs =
if nonempty xs then
let x, ys = hd xs, tl xs
if nonempty ys then
let y, zs = hd ys, tl ys
consl (x+y) (lazy (pairSum zs))
else consl x (lazy nil) )
else nil

There are other variations presented in the paper, including
parameterized patterns.  These are nice for doing things like regular
expression matching.  Again, from the paper:

let (|ParseRE|_|) re s =
let m = Regex(re).Match(s)
if m.Success
then Some [ for x in m.Groups -> x.Value ]
else None

let swap s =
match s with
| ParseRE "(\w+)-(\w+)" [l;r] -> r ^ "-" ^ l   (* See below *)
| _ -> s

The matching syntax here is a bit confusing because it can be hard to
tell where parameters end and patterns begin.  In the example above,
"(\w+)-(\w+)" is a parameter and [l;r] is a pattern.  There's
definitely room for improvement over this syntax.

There are other variations and examples in the paper.  I'd definitely
recommend reading it.  If you still can't get it from the website I
can forward you a copy off-list.

Cheers,
-n8

--
>>>-- Nathaniel Gray -- Caltech Computer Science ------>
>>>-- Mojave Project -- http://mojave.cs.caltech.edu -->

```