[plt-scheme] define-union

From: Robby Findler (robby at cs.uchicago.edu)
Date: Fri Apr 18 21:59:12 EDT 2003

At Fri, 18 Apr 2003 21:29:59 -0400, "Anton van Straaten" wrote:
>   For list-related administrative tasks:
>   http://list.cs.brown.edu/mailman/listinfo/plt-scheme
> Stephen Bloch wrote:
> > Example:
> > (define-struct foo (a b))
> > (define-struct bar (c d e))
> > (define-union snark (foo bar number))
> > 
> > Semantics: checks that foo, bar, and number are in fact known types, 
> > with one-place discriminator predicates foo?, bar?, and number? 
> > respectively, and does the equivalent of
> > (define (snark? x)
> >     (if (or (foo? x) (bar? x) (number? x)))
> How about modifying your spec slightly to allow this:
> 	(define-union snark? (foo? bar? number?))
> ...which would allow you to use this:
> 	(define-syntax define-union
> 	  (syntax-rules ()
> 	    ((_ name (pred ...))
> 	     (define (name x) (or (pred x) ...)))))
> ...which has the virtue of being very simple to implement and understand.

You can do better with the error checking:

(module du mzscheme
  (provide define-union)
  (define-syntax (define-union stx)
    (syntax-case stx ()
      [(_ name (pred ...))
       (identifier? (syntax name))
       (with-syntax ([(pred-x ...) (generate-temporaries (syntax (pred ...)))])
         (syntax/loc stx
           (define name
             (let ([pred-x pred] ...)
               (unless (and (procedure? pred-x)
                            (procedure-arity-includes? pred-x 1))
                 (error 'define-union "not a predicate: ~e" pred-x)) ...
               (lambda (x)
                 (or (pred-x x) ...))))))])))

and you might call it define-union-predicate or something, too.

FWIW, Matthew, Shriram, Matthias and I've been tossing around ideas
like that in private and I believe that we now know how to turn data
definitions and contracts of into checkable artifacts (Ie, the computer
understands and enforces them rather than just being commented out
stuff), without having to introduce any new cognative barriers (types
systems or static analyses or anything like that). Of course, this kind
of a change requires massive changes to the book to support it so we've
not yet really started to talk about it too seriously. (plus, there are
two competing proposals that we will have to meet and talk about).

In short, we know that this is a problem and are working on it.


Posted on the users mailing list.