[plt-scheme] Pattern matching question

From: Matt Jadud (mcj4 at kent.ac.uk)
Date: Tue Feb 14 06:32:29 EST 2006

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]

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.


Posted on the users mailing list.