我正在研究 Clojure 算法来解决这里提出的问题:http: //spin.atomicobject.com/2011/05/31/use-clojure-to-move-drugs-a-programming-challenge/我'我遇到了麻烦。
我正在使用递归算法(可能不是开始的正确选择),遍历按最高到最低价值重量比排序的“娃娃”结构向量。相关代码为:
(defn get-carryable-dolls
[dolls carryable-dolls]
(def doll (first dolls)) ;initializing for use in multiple places
(def rest-dolls (rest dolls)) ;initializing for use in multiple places
(
if (will-fit? doll (get-weight-sum carryable-dolls))
( ;will fit
(
if
(= carryable-dolls {})
(def new-doll-set [doll]) ;First trip, get rid of empty set by initializing new
(def new-doll-set (flatten [doll carryable-dolls])) ;otherwise, flatten set into vector of structs
)
;tests to see if we have any more dolls to test, and if so, recurses. Otherwise, should pass the resultant vector
;up the stack. it appears to be the "else" potion of this if statement that is giving me problems.
(if (not= () rest-dolls) (get-carryable-dolls rest-dolls new-doll-set) (vec new-dolls))
)
( ;will not fit
;gets the rest of the dolls, and sends them on without modifying the vector of structs
;it appears to be the "else" potion of this if statement that is giving me problems.
(if (not= () rest-dolls) (get-carryable-dolls rest-dolls carryable-dolls) (vec carryable-dolls))
)
)
)
该代码工作正常;returnable-dolls 包含要作为解决方案返回的娃娃结构的所需向量。不幸的是,当我尝试将 returnable-dolls 向量返回到调用位置时,我收到以下错误:
CompilerException clojure.lang.ArityException: Wrong number of args (0) passed to: PersistentVector,compiling:(drugmover\tests.clj:83)
第 82-83 行内容如下:
(def empty-dolls {})
(def designated-dolls (get-carryable-dolls sorted-values empty-dolls))
我对可能导致编译器错误的问题感到困惑,并且由于 Clojure 似乎更喜欢简洁的错误消息而不是堆栈跟踪(或者至少 Clooj 中的 REPL 功能确实如此),我不知道如何要解决这个问题。如果有人有任何建议,我将不胜感激!
提前致谢。
编辑:
我已经用答案和评论中的人建议的修复修改了代码,并提供了一些评论来帮助说明正在进行的流控制。希望通过说明我的想法,有人能够告诉我我哪里出错了。