【问题标题】:racket match syntax quasiquote and question mark球拍匹配语法准引号和问号
【发布时间】:2013-07-12 10:17:01
【问题描述】:

我正在尝试理解球拍的模式匹配文档,并且有一些类似以下的问题,我无法解析它。

  • (quasiquote qp) — 引入了一个 quasipattern,其中标识符匹配符号。与 quasiquote 表达形式一样,unquote 和 unquote-splicing 逃回正常模式。

http://docs.racket-lang.org/reference/match.html

例子:

> (match '(1 2 3)
    [`(,1 ,a ,(? odd? b)) (list a b)])

'(2 3)

没有解释这个例子,以及“标识符如何匹配符号”?我猜这是匹配'(1 2 3) 到模式'(1, a, b) 并且b 是奇怪的,但是为什么`(,1 ,a ,(? odd? b)) 不是`(1 a (? odd? b)),它需要在列表成员之间使用逗号吗?特别是`(,?为什么这样?所以字符串!

谢谢!

【问题讨论】:

    标签: lisp scheme pattern-matching racket


    【解决方案1】:

    如果您不熟悉准引用,那么您可能会熟悉match 中的list 模式,然后了解一般的准引用。那么将两者放在一起会更容易理解。

    为什么?因为 quasiquote “仅”是您可以使用 list 编写的内容的简写或替代。虽然我不知道实际的发展历史,但我想match 的作者是从listconsstruct 等模式开始的。然后有人指出,“嘿,有时我更喜欢使用准引用来描述list”,他们也添加了准引用。

    #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
    

    【讨论】:

      猜你喜欢
      • 2013-04-10
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 2011-08-29
      • 1970-01-01
      • 2014-07-06
      相关资源
      最近更新 更多