代码之家  ›  专栏  ›  技术社区  ›  Benno

这个Clojure程序有什么问题?

  •  5
  • Benno  · 技术社区  · 16 年前

    我最近开始阅读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)
    

    <#CompilerException java.lang.IllegalArgumentException: Wrong number of args passed to: problem31$eval--25$make-combination-counter--27$recurse--29$fn (NO_SOURCE_FILE:0)>
    

    2 回复  |  直到 16 年前
        1
  •  13
  •   TacticalCoder    13 年前

    三个建议可能会让你的生活在这里更轻松:

    1. Wrong number of args passed to: problem31$eval--25$make-combination-counter--27$recurse--29$fn (NO_SOURCE_FILE:0)> $fn 最后是匿名函数,它告诉它是在recurse内部声明的,recurse是在内部声明的 make-combination-counter 。有两个匿名函数可供选择。

    2. 如果将源代码保存在文件中并将其作为脚本执行,它将为您提供包含文件中行号的完整堆栈跟踪。

      at net.projecteuler.problem31$apply_if__9.invoke(problem31.clj:7)
      

      请注意,您还可以通过检查*e来检查REPL中的最后一个异常和堆栈跟踪,例如:(.stackTrace*e)堆栈跟踪起初相当令人望而生畏,因为它抛出了所有Java内部。你需要学会忽略这些,只需查找引用你代码的行。这对你来说很容易,因为它们都是从 net.projecteuler

    3. (fn check-max [x] (<= (+ current-sum x) max-sum))
      

    apply map 这个程序似乎奏效了。

    最后,如果你想检查你可能想研究的值 clojure-contrib.logging EXPR = VALUE ,这可能很方便。同样在该小组中,许多人发布了完整的追踪解决方案。总会有值得信赖的人 println

        2
  •  2
  •   Arthur Ulfeldt    16 年前

    不要对我进行REPL,尽管它看起来像:

    (defn apply-if [pred-fun fun coll]
      (apply fun (filter pred-fun coll)))
    

    '(1 2 3 4 5) 过滤掉其中一些 '(1 3 5) (fun 1 3 5)

    看起来它正在被调用 (apply-if (fn [x] 作为一个单一的论点。

    推荐文章