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))))
因為局部的=>已經被改變了含義,不能匹配到包含=>的文法規則了。