我最近开始阅读 Paul Grahams 的《On Lisp》,并学习 Clojure,所以这里可能有一些非常明显的错误,但我看不出来:(这是一个项目欧拉问题,显然)
(ns net.projecteuler.problem31)
(def paths (ref #{}))
; apply fun to all elements of coll for which pred-fun returns true
(defn apply-if [pred-fun fun coll]
(apply fun (filter pred-fun coll)))
(defn make-combination-counter [coin-values]
(fn recurse
([sum] (recurse sum 0 '()))
([max-sum current-sum coin-path]
(if (= max-sum current-sum)
; if we've recursed to the bottom, add current path to paths
(dosync (ref-set paths (conj @paths (sort coin-path))))
; else go on recursing
(apply-if (fn [x] (<= (+ current-sum x) max-sum))
(fn [x] (recurse max-sum (+ x current-sum) (cons x coin-path)))
coin-values)))))
(def count-currency-combinations (make-combination-counter '(1 2 5 10 20 50 100 200)))
(count-currency-combinations 200)
当我在REPL中运行最后一行代码时,我会出现错误:
<#CompilerException java.lang.IllegalArgumentException: Wrong number of args passed to: problem31$eval--25$make-combination-counter--27$recurse--29$fn (NO_SOURCE_FILE:0)>
除了问题在哪里这个问题之外,更有趣的问题是:如何调试它?错误信息并不是很有用,我还没有找到一种好的单步调试Clojure代码的方法,也不能每次遇到问题都去在Stack Overflow上问。