gpt4 book ai didi

scheme - 评估顺序,SICP 练习

转载 作者:行者123 更新时间:2023-12-03 22:45:12 27 4
gpt4 key购买 nike

所以,我正在努力通过 SICP。
第 4 章的第一个练习是:

Exercise 4.1. Notice that we cannot tell whether the metacircular evaluator evaluates operands from left to right or from right to left. Its evaluation order is inherited from the underlying Lisp: If the arguments to cons in list-of-values are evaluated from left to right, then list-of-values will evaluate operands from left to right; and if the arguments to cons are evaluated from right to left, then list-of-values will evaluate operands from right to left. Write a version of list-of-values that evaluates operands from left to right regardless of the order of evaluation in the underlying Lisp. Also write a version oflist-of-values that evaluates operands from right to left.



原来的功能是
(define (list-of-values exps env)
(if (no-operands? exps)
'()
(cons (eval (first-operand exps) env)
(list-of-values (rest-operands exps) env))))

我的解决方案如下:
;;; left-to-right
(define (list-of-values-l2r exps env)
(if (no-operands? exps)
'()
(let ((first-exp (eval (first-operand exps) env)))
(cons first-exp
(list-of-values-l2r (rest-operands exps) env)))))

;;; right-to-left
(define (list-of-values-r2l exps env)
(list-of-values-l2r (reverse exps) env))

但是,我不确定我所做的是否正确。我的直觉是 let 语句强制执行 eval,有人可以确认吗?

最佳答案

let只是语法糖,没有 let 的重写看起来像

(define (list-of-values-l2r exps env)
(if (no-operands? exps)
'()
((lambda (first-exp)
(cons first-exp
(list-of-values-l2r (rest-operands exps) env)))
(eval (first-operand exps) env))))

由于方案急于评估 (eval (first-operand exps) env)总是在应用函数之前求值。

关于scheme - 评估顺序,SICP 练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34319987/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com