gpt4 book ai didi

scheme - 在 Scheme 中使用 "do"

转载 作者:行者123 更新时间:2023-12-04 16:32:51 25 4
gpt4 key购买 nike

CODE SNIPPET 1 和 CODE SNIPPET 2 有什么区别?

;CODE SNIPPET 1
(define i 0)
(do ()
((= i 5)) ; Two sets of parentheses
(display i)
(set! i (+ i 1)))


;CODE SNIPPET 2
(define i 0)
(do ()
(= i 5) ; One set of parentheses
(display i)
(set! i (+ i 1)))

第一个代码片段产生 01234,第二个产生 5。这是怎么回事?额外的一组括号有什么作用?另外,我见过 [(= i 50)]用于代替 ((= i 5)) .有区别吗?谢谢!

最佳答案

do 表单的一般结构是这样的:

(do ((<variable1> <init1> <step1>)
...)
(<test> <expression> ...)
<command> ...)

释义 http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-Z-H-6.html#node_chap_5 ,每次迭代都从评估 <test> 开始,如果计算结果为真值, <expression> s 从左到右求值,最后一个值作为 do 的结果返回。形式。在你的第二个例子中 =将被评估为一个 bool 值,意思是真,然后 i 将被评估,最后 5 是表单的返回值。第一种情况 (= i 5)是测试和 do表单返回一个未定义的值。编写循环的常用方法更像是这样:
(do ((i 0 (+ i 1)))
((= i 5) i) ; maybe return the last value of the iteration
(display i))

您不需要显式更改循环变量,因为这是由 <step> 处理的。表达。

关于scheme - 在 Scheme 中使用 "do",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3199228/

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