12模式匹配

模式匹配支持任意的racket值,這正正正表達式匹配不同,regexp-math只能支持正則表達式和字符序列或比特序列比較。

  (match target-expr 
    [pattern expr ...+] ...)

匹配形式取到target-expr的結(jié)果,然后按順序匹配每一個模式。如果匹配成功,它將執(zhí)行相應(yīng)的expr序列來獲得match形式的結(jié)果。如果模式里面有變量,它們被當做匹配符對待,每一個變量都會綁定到expr相應(yīng)的輸入片段上面。
大部分Racket字面表達式都能被當做模式來匹配

  >(match 2
      [1 'one]
      [2 'two]
      [3 'three])
  'two
  >(match #f
      [#t 'yes]
      [#f 'no])
  'no
  >(match "apple"
      ['apple 'symbol]
      ["apple" 'string]
      [#f 'boolean])
   'string

構(gòu)造函數(shù)cons,list,和vector能被用來創(chuàng)建模式匹配paris,lists,和vectors
>(match '(1 2)
[(list 0 1) 'one]
[(list 1 2) 'two])
'two
>(match '(1 . 2)
[(list 1 2) 'list]
[(cons 1 2) 'pair])
'pair
>(match #(1 2)
[(list 1 2) 'list]
[(vector 1 2) 'vector])
'vector
struct構(gòu)造函數(shù)也能被使用在模式匹配

>(struct shoe (size color))
>(struct hat (size style))
>(match  (hat 23 'blowler)
    [(shoe 10 'white) "bottom"]
    [(hat 12 'bowler) "top"])
"top"

模式里非引用,非構(gòu)造的標識符是模式變量,用來綁定結(jié)果表達式。除了_,不綁定任何東西,但可以匹配所有東西。

>(match '(1)
    [(list x) (+ x 1)]
    [(list x y) (+ x y)])
2
>(match '(1 2)
    [(list x) (+ x 1)]
    [(list x y) (+ x y)])
3
>(match (hat 23 'bowler)
    [(shoe sz col) sz]
    [(hat sz stl) sz])
23
>(match (hat 11 'cowboy)
    [(shoe sz 'black) 'a-good-shoe]
    [(hat sz 'bowler) 'a-good-hat]
    [_ 'something-else])
'something-else

...省略號,當在列表或者向量里面,代表省略號之前的子模式會被匹配多次。如果子模式包含一個模式變量并帶有...,變量會被匹配多次,綁定結(jié)果則是一個匹配的列表。

>(match '(1 1 1)
    [(list 1 ...) 'ones]
    [_ 'other])
'ones
>(match '(1 1 2)
    [(list 1 ...) 'ones]
    [_ 'other])
'other
>(match '(1 2 3 4)
    [(list 1 x ... 4)  x])
'(2 3)
>(match (list (hat 23 'bowler) (hat 22 'pork-pie))
    [(list (hat sz style) ...)  (apply + sz)])
45

省略號能被內(nèi)嵌匹配內(nèi)嵌的重復(fù),在這種情況下,模式變臉能綁定匹配的列表組成的列表

>(match  '((! 1) (! 2 2) (! 3 3 3))
    [(list (list '! x ...) ...) x])
'((1) (2 2) (3 3 3))

`左單引號也能用來構(gòu)建匹配。例子如下(無法理解,翻譯無奈)

>(match `{with {x 1} {+ x 1}}
    [`{with {,id,rhs} ,body}
      `{{lambda {,id} ,body} ,rhs}])

match-let和match-lambda支持位置模式的綁定而不是必須是標識符的綁定。

>(match-let ([list x y z) '(1 2 30])
      (list z y x))
'(3 2 1)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容