[plt-scheme] Pattern matching question

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Tue Feb 14 07:37:08 EST 2006

On Feb 14, 2006, at 6:32 AM, Matt Jadud wrote:

> Hi all,
> I have a question that I feel should have a simple solution.
> Say I'm matching s-expressions, and building some kind of record 
> structure from them.
> (define (build-foo exp)
>   (match exp
>     [`(foo ,bar ,gee)
>       (make-foo (build-bar bar) (build-gee gee))]
>     [`(foo ,bar ,whoo)
>       (make-foo (build-bar bar) (build-whoo whoo))]
>     [else #f]
>     ))

The output-driven recipe would suggest that you write

  (match exp
    [`(foo ,bar ,gee-or-whoo) (make-foo (build-bar bar) 
(build-gee-or-whoo gee-or-whoo)]
    [else #f])

-- Matthias

> This is ambiguous, as the second pattern is shadowed by the first. I 
> could add a guard to each pattern (eg. (? bar? bar)), but this implies 
> I have to walk each subtree twice---once to check that something is a 
> bar? or gee?, and again to actually build the appropriate structure.
> Or, do I treat the guard as an implicit cata?
> [`(foo ,(? bar? bar) ,(? gee? gee))
>   (make-foo bar gee)]
> In this way, if it matches, it will come back with the subtree 
> built---otherwise, it comes back false? (Assuming, of course, that 
> `(foo ,bar ,gee) cannot actually be confused with `(foo ,bar ,whoo).)
> Perhaps this is more of a sanity check than anything else.
> Thanks,
> M
> _________________________________________________
>  For list-related administrative tasks:
>  http://list.cs.brown.edu/mailman/listinfo/plt-scheme

Posted on the users mailing list.