[racket] Pattern matching define macro
Thanks. I did look at define/match but:
(defpat (is-pos (list r c))
(and (member r (lgen 0 4))
(member c (lgen 0 r))))
seems nicer to me than:
(define/match (is-pos l)
[((list r c)) (and (member r (lgen 0 4))
(member c (lgen 0 r)))])
for two reasons:
1) It's odd to me to specify the l argument, and then never refer to it.
2) The syntax of the former seems less "noisy".
I can see the advantage of define/match when you have more than one pattern, and I think there's a disadvantage in introducing too many macros that are close to existing, standard, ones, but I *think* this is going to be a common enough situation for me that being slightly more concise and not creeping to the right may be worth it. I'll hold the opinion loosely though until I have a bunch more code reading/writing under my belt.
Brian
On Jul 12, 2014, at 1:21 PM, Jens Axel Søgaard wrote:
> Hi Brian,
>
> I think you want define/match.
>
> (define/match (is-pos l)
> [((list r c)) (and (member r (range 0 4))
> (member c (range 0 r)))])
>
>
> (is-pos '(2 5)) ; => #f
> (is-pos '(2 1)) ; => '(1)
>
> /Jens Axel
>
>
> 2014-07-12 18:53 GMT+02:00 Brian Adkins <racketusers at lojic.com>:
>> I'm porting more Haskell code to Racket as a learning exercise. When I got to this line:
>>
>> isPos (r,c) = elem r [0..4] && elem c [0..r]
>>
>> I first wrote this:
>>
>> (define (is-pos r c) (and (member r (lgen 0 4))
>> (member c (lgen 0 r))))
>>
>> where lgen is:
>>
>> (define (lgen m n) (build-list (+ 1 (- n m)) (λ (x) (+ x m))))
>>
>> I think (lgen 0 r) is a reasonable alternative to [0..r], and the minor additional length of the Racket version is fine.
>>
>> I then decided that I may prefer to a list of row/col instead of individual args and bumped into a need for destructuring a list, so I wrote this macro:
>>
>> (define-syntax defpat
>> (syntax-rules ()
>> [(_ (fn pat) b1 b2 ...)
>> (define fn (match-lambda [pat b1 b2 ...]))]))
>>
>> which allows:
>>
>> (defpat (is-pos (list r c)) (and (member r (lgen 0 4))
>> (member c (lgen 0 r))))
>>
>> The fact that this is such a common operation and I couldn't find anything built-in makes me think that I may be missing something. Is this a reasonable solution? Are there better alternatives?
>>
>> I suppose a better name might be in order since it's not matching one of several patterns; in this case, it's really just for destructuring a list more concisely.
>>
>> I'm still blown away by how easy it was to mold Racket closer to what I wanted. I've just barely begun learning macros, but syntax-rules made this pretty easy.
>>
>> I think the only thing that sticks out is the "list" function, but that seems like a reasonable sacrifice given the flexibility it allows for in more complicated patterns.
>>
>> Thanks,
>> Brian
>>
>> --
>> Brian Adkins
>> Lojic Technologies, LLC
>> http://lojic.com/
>>
>>
>> ____________________
>> Racket Users list:
>> http://lists.racket-lang.org/users
>
>
>
> --
> --
> Jens Axel Søgaard