[racket] Pattern matching define macro

From: Alexander D. Knauth (alexander at knauth.org)
Date: Sat Jul 12 22:17:24 EDT 2014

On Jul 12, 2014, at 6:43 PM, Brian Adkins <racketusers at lojic.com> wrote:

> On Jul 12, 2014, at 6:19 PM, Daniel Prager wrote:
> 
>> Hi Brian
>> 
>> r >= 0 && r <= 4 && c >= 0 && c <= r
>> 
>> 
>> implies
>> 
>> 0 <= c <= r <= 4
>> 
>> 
>> Or  using prefix and the variable-arity of <=:
>> 
>> (define (is-pos r c)
>> (<= 0 c r 4))
>> 
>> 
>> which I think works well for clarity, concision, and efficiency.
>> 
>> Dan
> 
> Very nice observation; I like it. I've always felt the variable-arity of lisp was a cool feature. I switched to a struct for the arg, but the following works:
> 
> (defpat (is-pos? (pos r c))
>  (<= 0 c r 4))
> 
> I probably won't keep my defpat macro, at least not in its present form (for one, it only handles a single arg); there's probably a balance between being concise and being general/flexible.

Although define/match is definitely more powerful, if you want it, this would probably be a good version of what you want that would handle multiple arguments:  (I’ll reply again if I get one to work with optional and/or keyword-arguments)
(define-syntax defpat
  (syntax-rules ()
    [(defpat (f arg-pat ...) body ...)
     (defpat f (match-lambda** [(arg-pat ...) body ...]))]
    [(defpat id expr)
     (define id expr)]))

> 
> I finished the program, but it's very raw - I haven't tried to match the Racket style, be idiomatic, etc., just rushed through it to get a rough idea of how it compares:
> 
> https://gist.github.com/lojic/14aefacc29ab5a88fa98
> 
> I'll come back to it after I get some more experience and improve it. Despite the questionable utility of these exercises, I always run into something that causes me to learn something valuable about Racket.
> 
> 
> ____________________
>  Racket Users list:
>  http://lists.racket-lang.org/users



Posted on the users mailing list.