gpt4 book ai didi

clojure - Clojure cond 部分的评估

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

尝试用 Clojure 做“计算机程序的结构和解释”中的练习 1.16(fast-exp 的迭代版本),我想出了这个:

(defn fast-it-exp [base exp res]
(cond (= exp 0) res
(odd? exp) fast-it-exp base (- exp 1) (* base res)
:else fast-it-exp base (/ exp 2) (* base base res)))

尝试一下:

user=> (fast-it-exp 0 0 10)
10 ;yep
user=> (fast-it-exp 2 2 2)
1 ;no...
user=> (fast-it-exp 1 1 1)
#<user$fast_it_exp__59 user$fast_it_exp__59@138c63> ;huh?!

似乎 cond 表达式的“奇数”部分返回一个函数而不是求值。为什么?我尝试在谓词后面的表达式周围加上括号,但这似乎是不正确的语法,这是我能想到的最好的方法。我正在使用 Clojure 的 rev 1146。

最佳答案

试试这个:

 (defn fast-it-exp [base exp res]
(cond (= exp 0) res
(odd? exp) (fast-it-exp base (- exp 1) (* base res))
:else (fast-it-exp base (/ exp 2) (* base base res))))

我没有方便的 REPL,但看起来像你想要的。

关于clojure - Clojure cond 部分的评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/455184/

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