[Scheme]一个Scheme的Metacircular evaluator

时间:2023-12-18 08:39:50

这个解释器可以用来跑前面两篇文章的例子,所以一并扔出来,三部曲哈哈。

Lisp内置的S-expression相当于解析好的语法树,而借助quasiquote和unquote又很容易进行语法树层面的变换,所以Lisp的自举和扩展都很容易。

相对而言,其他语言有入门教材就讲怎么实现语言自身的解释器的吗?至少命令式语言恐怕不容易,尤其是中缀表示法的语言,Parser这一关会卡死很多人。

这个解释器的典型特性包括currying、call/cc,所以可以用来跑前面的lambda calculus和yin-yang-puzzle例子:

 #lang racket

 (require racket/match)
;------------------------------
(define (eval env e k)
(match e
[(? symbol?) (k (cdr (assq e env)))]
[(list 'lambda arg-list exp-list ...)
(let ([arg-list (if (empty? arg-list) '(_) arg-list)])
(cond
[(> (length arg-list) 1)
(eval env `(lambda (,(car arg-list)) (lambda ,(cdr arg-list) ,@exp-list)) k)]
[(> (length exp-list) 1)
(eval env `(lambda ,arg-list ((lambda (_) ,@(cdr exp-list)) ,(car exp-list))) k)]
[else (k
(lambda (arg k2)
(eval (cons (cons (car arg-list) arg) env) (car exp-list) k2)))]))]
[(list p arg-list ...)
(let ([arg-list (if (empty? arg-list) '(print) arg-list)])
(if (= 1 (length arg-list))
(eval env p (lambda (p)
(eval env (car arg-list) (lambda (arg)
(p arg k)))))
(eval env `((,p ,(car arg-list)) ,@(cdr arg-list)) k)))]
)
)
;------------------------------
(define G (list
(cons 'print (lambda (n k)
(n (lambda (v k2)
(k2 (add1 v)))
(lambda (v)
(v 0 (lambda (v) (k (print v))))))))
(cons 'newline (lambda (_ k)
(k (newline))))
(cons 'call/cc (lambda (f k)
(f (lambda (v k2) (k v)) k)))
))
;------------------------------
(eval G (read) identity)

用到了racket/match,当然,自己弄一个简单的linear pattern matcher也很容易,不过我就不做让事情复杂化的尝试了。

这是前文lambda calculus的例子,一字不变:

 ((lambda (zero one add mul pow sub1 true false and or)
((lambda (sub not zero? two Y)
((lambda (less-equal? equal? three four)
;------------------------------
((lambda (for-each fib)
(for-each (lambda (i) (print (fib zero one zero i))(newline)) zero (mul four four))
)
(Y
(lambda (self)
(lambda (f i n)
(f i)
(((equal? i n)
(lambda () i)
(lambda () (self f (add i one) n))))
)
))
(Y
(lambda (self)
(lambda (a b i n)
(((equal? i n)
(lambda () a)
(lambda () (self b (add a b) (add i one) n))))
)
))
)
;------------------------------
)
(lambda (m n) (zero? (sub m n)))
(lambda (m n) (and (zero? (sub m n)) (zero? (sub n m))))
(add two one)
(add two two)
))
(lambda (m n) (n sub1 m))
(lambda (a) (a false true))
(lambda (n) (n (lambda (x) false) true))
(add one one)
(lambda (f)
((lambda (g) (g g))
(lambda (g) (f (lambda (a) ((g g) a))))))
))
(lambda (f x) x)
(lambda (f x) (f x))
(lambda (m n f x) (m f (n f x)))
(lambda (m n f) (m (n f)))
(lambda (e b) (e b))
(lambda (n f x)
(((n
(lambda (g h) (h (g f))))
(lambda (u) x))
(lambda (u) u)))
(lambda (a b) a)
(lambda (a b) b)
(lambda (a b) (a b a))
(lambda (a b) (a a b))
)

这是yin-yang-puzzle的例子,人肉展开了let*

 ((lambda (yin)
((lambda (yang)
(yin yang))
((lambda (c) (print (lambda (f x) x)) c)
(call/cc (lambda (k) k)))))
((lambda (c) (print (lambda (f x) (f x))) c)
(call/cc (lambda (k) k))))