1
我與SICP一起工作,運動2.29-b讓我有機會在穿越手機和分支時獲得延續傳球風格。SICP,延續傳球風格和Clojure的蹦牀
爲了簡化故事,每個手機都有左右分支,它們由長度和數字權重或其他手機組成。這個問題要求找到手機的總重量。
第一相互遞歸解決方案之後,很簡單,我嘗試併成功實施了CPS'之一:
(defn total-weight-cps [mobile]
(letfn
[(branch-weight-cps
[branch kont]
(let [structure (branch-structure branch)]
(if (mobile? (branch-structure branch))
(do (println "then " structure) (kont (traverse-mobile-cps structure identity)))
(do (println "else " structure) (kont structure)))))
(traverse-mobile-cps
[mobile kont]
(branch-weight-cps (left-branch mobile)
(fn [left-weight]
(branch-weight-cps (right-branch mobile)
(fn [right-weight] (kont (+ left-weight right-weight)))))))]
(traverse-mobile-cps mobile identity)))
在這一點上,我曾嘗試申請蹦牀,以維護我的籌碼。但有以下例外吹:
java.lang.ClassCastException: sicp_clojure.2_1_exercises_2_24_2_32$total_weight_STAR_$traverse_mobile_cps__6694$fn__6695$fn__6696$fn__6697 cannot be cast to java.lang.Number
Numbers.java:126 clojure.lang.Numbers.add
.../git/sicp-clojure/src/sicp_clojure/2_1_exercises_2_24_2_32.clj:185 sicp-clojure.2-1-exercises-2-24-2-32/total-weight*[fn]
core.clj:5801 clojure.core/trampoline
core.clj:5806 clojure.core/trampoline
RestFn.java:439 clojure.lang.RestFn.invoke
.../git/sicp-clojure/src/sicp_clojure/2_1_exercises_2_24_2_32.clj:186 sicp-clojure.2-1-exercises-2-24-2-32/total-weight*
使用蹦牀,以下的優秀link的代碼是:
(defn total-weight* [mobile]
(letfn
[(branch-weight-cps
[branch kont]
(let [structure (branch-structure branch)]
(if (mobile? (branch-structure branch))
(do (println "then " structure) (kont (traverse-mobile-cps structure identity)))
(do (println "else " structure) (kont structure)))))
(traverse-mobile-cps
[mobile kont]
(branch-weight-cps (left-branch mobile)
(fn [left-weight]
(branch-weight-cps (right-branch mobile)
(fn [right-weight] #(kont (+ left-weight right-weight)))))))]
(trampoline traverse-mobile-cps mobile identity)))
最後一些樣本數據:
(def branch11 (make-branch 1 1))
(def branch22 (make-branch 2 2))
(def branch36 (make-branch 3 6))
(def branch43 (make-branch 4 3))
(def mobile11-43 (make-mobile branch11 branch43))
(def mobile36-22 (make-mobile branch36 branch22))
(def branch5m1143 (make-branch 5 mobile11-43))
(def branch7m3622 (make-branch 7 mobile36-22))
(def mobile5m1143-7m3622 (make-mobile branch5m1143 branch7m3622))
(total-weight* mobile5m1143-7m3622)
爲什麼它爆炸?
你問爲什麼它炸燬?你從來沒有真正保持你的問題。 – user100464 2014-10-19 18:55:14
對不起,是的,編輯。 – 2014-10-20 11:18:06