[plt-scheme] matching/dispatching a la Erlang

From: Bruce Hauman (bhauman at cs.wcu.edu)
Date: Thu Aug 28 17:17:18 EDT 2003

On Thu, 28 Aug 2003, David Van Horn wrote:

>   For list-related administrative tasks:
>   http://list.cs.brown.edu/mailman/listinfo/plt-scheme
>
> William Sprague wrote:
> > I want to be able to do something like the following, where
> > "case-on-steroids" is my desired operator:
> >
> > (define (choose input)
> >   (case-on-steroids (X Y)       ; define X and Y as free variables
> >     ((X X Y) (+ X Y))           ; matches (input 1 1 2), bind X->1, Y->2
> >     ((1 X (2 Y) X) (* X Y))     ; matches (input 1 100 '(2 300) 100)
> >                                 ; X->100, Y->300
> >     (_ 'whatever))))            ; matches anything no bindings

This style of matching is now available in the latest release of the
match.ss library.

-Bruce


>
> I believe you want Bigloo-style pattern matching.  I can't remember if there's
> a PLT package that provides such matching, but in Bigloo it would look like:
>
> (define (choose input)
>   (match-case input
>     (((kwote input) ?x ?x ?y)       (+ x y))
>     (((kwote input) 1 ?x (2 ?y) ?x) (* x y))
>     (?- 'whatever)))
>
> (choose '(input 1 1 2)) ;=> 3
> (choose '(input 1 100 (2 300) 100)) ;=> 3000
>
> You could write it equivalently in PLT as:
>
> (require (lib "match.ss"))
> (define choose
>   (match-lambda
>     [('input x-1 x-2 y)
>      (=> fail)
>      (if (eq? x-1 x-2)
>          (+ x-1 y)
>          (fail))]
>     [('input 1 x-1 (2 y) x-2)
>      (=> fail)
>      (if (eq? x-1 x-2)
>          (* x-1 y)
>          (fail))]
>     [_ 'whatever]))
>
> HTH
>
> -d
>
>
>


Posted on the users mailing list.