Scheme語言自訂文法結構時的Literal identifier

來源:互聯網
上載者:User

Scheme語言允許使用者使用let-syntax等機制自訂特殊的文法結構。定義這種文法結構時使用的Pattern language裡有一個不太顯眼的Literal identifier,就是下面文法中的<literals>:

(syntax-rules <literals> <syntax rule> ... )

Scheme標準R5RS裡對Literal identifier的闡釋比較晦澀難懂。我根據自己的理解寫了一個小例子,大概可以起到補充說明的作用:

;;; 不使用Literal identifier時定義文法z
(define-syntax z
  (syntax-rules ()
    ((z (+ x y)) (+ x y))))
;;; 下面一行的結果是 7
(z (+ 3 4))
;;; 下面一行的結果是 -1,在局部改變意義後的加號起了作用
(let ((+ -)) (z (+ 3 4)))

;;; 使用Literal identifier時定義文法z
(define-syntax z
  (syntax-rules (+)
    ((z (+ x y)) (+ x y))))
;;; 下面一行的結果仍是 7
(z (+ 3 4))
;;; 下面這一行報錯:z: bad syntax in: (z (+ 3 4))
;;; 與定義文法時含義不同(其實是綁定不同)的加號無法應用到這樣的文法中
(let ((+ -)) (z (+ 3 4)))

有了上面這個例子,R5RS裡提到的那個較複雜的例子就比較好理解了:

(define-syntax cond
  (syntax-rules (else =>)
    ((cond (else result1 result2 ...))
     (begin result1 result2 ...))
    ((cond (test => result))
     (let ((temp test))
       (if temp (result temp))))
    ((cond (test => result) clause1 clause2 ...)
     (let ((temp test))
       (if temp
           (result temp)
           (cond clause1 clause2 ...))))
    ((cond (test)) test)
    ((cond (test) clause1 clause2 ...)
     (let ((temp test))
       (if temp
           temp
           (cond clause1 clause2 ...))))
    ((cond (test result1 result2 ...))
     (if test (begin result1 result2 ...)))
    ((cond (test result1 result2 ...)
           clause1 clause2 ...)
     (if test
         (begin result1 result2 ...)
         (cond clause1 clause2 ...)))))

在上面這樣的cond定義基礎上,下面的代碼

(let ((=> #f))
  (cond (#t => 'ok))) ;  =) ok

將被解釋為(這裡的=>被視為變數而不是文法元素)

(let ((=> #f))
  (if #t (begin => 'ok)))

而不是

(let ((=> #f))
  (let ((temp #t))
    (if temp ('ok temp))))

因為局部的=>已經被改變了含義,不能匹配到包含=>的文法規則了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.