Lar*_*ren 6 functional-programming clojure
尝试使用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)))
Run Code Online (Sandbox Code Playgroud)
尝试一下:
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?!
Run Code Online (Sandbox Code Playgroud)
似乎cond表达式的"奇数"部分返回一个函数而不是求值.为什么?我已经尝试在谓词后面的表达式附加括号,但这似乎是不正确的语法,这是我能够想出的最好的.我正在使用Clojure的rev 1146.
小智 11
试试这个:
(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))))
Run Code Online (Sandbox Code Playgroud)
我没有方便的REPL,但看起来像你想要的.
小智 6
基本上,你写的内容可以重新格式化为:
(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)))
Run Code Online (Sandbox Code Playgroud)
所以:
user=> (fast-it-exp 0 0 10) ; (= exp 0) => res
10 ;yep
user=> (fast-it-exp 2 2 2) ; base => (- exp 1)
1 ;no...
user=> (fast-it-exp 1 1 1) ; (odd? exp) => fast-it-exp
#<user$fast_it_exp__59 user$fast_it_exp__59@138c63> ;huh?!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5182 次 |
| 最近记录: |