[racket] matching behavior in dispatch-rules

From: Jay McCarthy (jay.mccarthy at gmail.com)
Date: Tue Jan 21 12:10:02 EST 2014

Hi Matthew,

In your 'match' examples, you are printing out the result of "matched"
which is bound by (and matched ...) on the outside of the match
pattern, so it is equivalent to

(define matched (list ....))
(match matched
 [...inside... ....])

This idiom doesn't really have anything to do with what dispatch-rules
does, because dispatch-rules doesn't have "and". Instead,
dispatch-rules behaves more like a normal "match" where only the names
are bound/passed-to-the-function.

Jay


On Sat, Jan 18, 2014 at 9:59 PM, Matthew Butterick <mb at mbtype.com> wrote:
> If you run this code:
>
> ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
> #lang racket
> (require web-server/dispatch
>          web-server/http/request-structs
>          net/url)
>
> (define (url->request u)
>   (make-request #"GET" (string->url u) empty
>                 (delay empty) #f "1.2.3.4" 80 "4.3.2.1"))
>
> (define-values (test-dispatch sum-url)
>   (dispatch-rules
>    [((? string?) "foo" (? string?)) test-route]
>    [((? string?) (? (λ(x) (equal? x "bar"))) (? string?)) test-route]))
>
> (define (test-route req . args)
>   (displayln (format "args = ~v" args)))
>
> (test-dispatch (url->request "http://url.com/first-string/foo/second-string.html"))
> (test-dispatch (url->request "http://url.com/first-string/bar/second-string.html"))
> ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
>
> You'll get this:
>
> args = '("first-string" "second-string.html")
> args = '("first-string" "bar" "second-string.html")
>
>
> Whereas if you use these patterns with regular match, like so:
>
> (match (list "first-string" "foo" "second-string.html")
>     [(and matched (list (? string?) "foo" (? string?))) matched])
>
> (match (list "first-string" "bar" "second-string.html")
>     [(and matched (list (? string?) (? (λ(x) (equal? x "bar"))) (? string?))) matched])
>
> You'll get:
>
> '("first-string" "foo" "second-string.html")
> '("first-string" "bar" "second-string.html")
>
>
> Thus my question: why doesn't the literal "foo" in the first pattern under dispatch-rules become one of the matched items, as it does with regular match?
>
>
> ____________________
>   Racket Users list:
>   http://lists.racket-lang.org/users



-- 
Jay McCarthy <jay at cs.byu.edu>
Assistant Professor / Brigham Young University
http://faculty.cs.byu.edu/~jay

"The glory of God is Intelligence" - D&C 93


Posted on the users mailing list.