我试图在方案中解释lambda。这是我的代码:
(define get-operator (lambda (op-symbol)
(cond
((equal? op-symbol '+) +)
((equal? op-symbol '-) -)
((equal? op-symbol '*) *)
((equal? op-symbol '/) /)
(else (error "interpret: operator not implemented -->" op-symbol)))))
(define (apply-lambda clos actuals)
(let* ((lam (cadr clos))
(def-env (caddr clos))
(formals (cadr lam))
(body (caddr lam))
(new-env (bind-all formals actuals def-env)))
(val-body new-env)))
(define interpret (lambda (e env)
(cond
((number? e) e)
((symbol? e) (get-value e env))
((not (list? e)) (error "interpret: cannot evaluate -->" e))
((if-stmt? e) (if (eq? (cadr e) 0)
(interpret (cadddr e) env)
(interpret (caddr e) env)))
((let-stmt? e) ;;GoZoner's part of code
(let ((names (map car (cadr e)))
(inits (map cadr (cadr e))))
;; Evaluate inits in env
(let ((vals (map (lambda (init) (interpret init env)) inits)))
;; Extend env with names+vals
(let ((new-env (append (map cons names vals) env)))
;; Eval body in new env
(interpret (caddr e) new-env)))))
((lambda-stmt? e) (apply-lambda e env))
(else
(let ((operands (map interpret (cdr e) (make-list (length (cdr e)) env)))
(operator (get-operator (car e))))
(apply operator operands))))))
当我尝试输入((lambda (n) (+ n 2)) 5)
时,我收到一条错误消息“作为()
的参数传递的对象safe-car
不是一对”。为什么会出现这种情况?我确信lambda-stmt?
函数运行良好,所以我没有在这里写,对apply-lambda
的解释有问题,但我找不到它。
答案 0 :(得分:0)
这似乎不对:
(lambda-stmt? e)
应该是:
(lambda-stmt? (car e))
答案 1 :(得分:0)
解释lambda
本身是微不足道的。
(define (make-closure formals body env)
`(CLOSURE ,formals ,body ,env))
(define closure-formals cadr)
(define closure-body caddr)
(define closure-env cadddr)
(define (procedure? thing)
(and (pair? thing) (eq? 'CLOSURE (car thing))))
然后在翻译中:
((lambda-stmt? e) (make-closure (cadr e) (caddr) env))
然后,您必须更改函数/运算符(您的'else'子句)的应用程序来处理过程(除了数学运算之外)。并且,您需要在调用时将该过程应用于其参数 - 但这是很多,如let
(将lambda
形式绑定到参数,解释{{1在新环境中的身体)。
[添加...]
我开始这么想:
lambda