Reputation: 7081
I am trying to understand pattern match document of racket and have some questions like the following, I can't parse it.
http://docs.racket-lang.org/reference/match.html
Example:
> (match '(1 2 3)
[`(,1 ,a ,(? odd? b)) (list a b)])
'(2 3)
It doesn't explain this example, and how "identifiers match symbols"? I guess it is match '(1 2 3)
to pattern '(1, a, b)
and b is odd, but why `(,1 ,a ,(? odd? b))
not `(1 a (? odd? b))
, whey it needs commas in between list members? Especially `(,
? Why that way? So string!
Thanks!
Upvotes: 2
Views: 2687
Reputation: 16250
If you're not familiar with quasiquoting, then you might to get comfortable with list
patterns in match
, then learn about quasiquoting in general. Then putting the two together will be easier to understand.
Why? Because quasiquote is "only" a shorthand or alternative for what you can write with list
. Although I don't know the actual development history, I imagine that the author(s) of match
started off with patterns like list
, cons
, struct
and so on. Then someone pointed out, "hey, sometimes I prefer to describe a list
using quasiquoting" and they added quasiquoting, too.
#lang racket
(list 1 2 3)
; '(1 2 3)
'(1 2 3)
; '(1 2 3)
(define a 100)
;; With `list`, the value of `a` will be used:
(list 1 2 a)
; '(1 2 100)
;; With quasiquote, the value of `a` will be used:
`(1 2 ,a)
; '(1 2 100)
;; With plain quote, `a` will be treated as the symbol 'a:
'(1 2 a)
; '(1 2 a)
;; Using `list` pattern
(match '(1 2 3)
[(list a b c) (values a b c)])
; 1 2 3
;; Using a quasiquote pattern that's equivalent:
(match '(1 2 3)
[`(,a ,b ,c) (values a b c)])
; 1 2 3
;; Using a quote pattern doesn't work:
(match '(1 2 3)
['(a b c) (values a b c)])
; error: a b c are unbound identifiers
;; ...becuase that pattern matches a list of the symbols 'a 'b 'c
(match '(a b c)
['(a b c) #t])
; #t
Upvotes: 5