我正在尝试在方案中解释 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
但我找不到它。