我想了解为该问题设计的以下代码是如何工作的:“给定一个整数序列,找到一个使其元素总和最大化的连续子序列”
defn max-subseq-sum [coll]
(->> (take-while seq (iterate rest coll)) ; tails (1)
(mapcat #(reductions conj [] %)) ; inits (2)
(apply max-key #(reduce + %)))) ; max sum
Run Code Online (Sandbox Code Playgroud)
所以我想看看表格 (1)、(2) 和其他表格的输出。我可以在 Cursive 中设置断点,但我不知道如何获得这些值。我试图定义一个语言环境变量,例如
(defn max-subseq-sum [coll]
(->> (take-while seq (iterate rest coll)) ; tails
(let [d #(reductions conj [] %)]
d ) ; inits
(apply max-key #(reduce + %)))
)
(max-subseq-sum [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1])
Run Code Online (Sandbox Code Playgroud)
但我仍然不明白如何看到 d,例如
如何解决这个问题呢?
可以将一个打印并返回其输入的简单函数插入到链中:
(defn debug [x]
(println x)
x)
(defn max-subseq-sum [coll]
(->> (take-while seq (iterate rest coll))
(debug)
(mapcat #(reductions conj [] %))
(apply max-key #(reduce + %))))
(max-subseq-sum [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1])
([-1 -2 3 5 6 -2 -1 4 -4 2 -1] (-2 3 5 6 -2 -1 4 -4 2 -1) (3 5 6 -2 -1 4 -4 2 -1) (5 6 -2 -1 4 -4 2 -1) (6 -2 -1 4 -4 2 -1) (-2 -1 4 -4 2 -1) (-1 4 -4 2 -1) (4 -4 2 -1) (-4 2 -1) (2 -1) (-1))
=> [3 5 6 -2 -1 4]
Run Code Online (Sandbox Code Playgroud)
或者,如果您想要更好的跟踪并且不介意大批量,您可以使用在打印输出中包含表达式的宏:
(defmacro debugM [expr]
`(let [x# ~expr] ; Save the result of the expression so it isn't evaluated twice
(println '~expr "\n\t" x#)
x#))
(defn max-subseq-sum [coll]
(->> (take-while seq (iterate rest coll))
(debugM)
(mapcat #(reductions conj [] %))
(apply max-key #(reduce + %))))
(max-subseq-sum [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1])
(take-while seq (iterate rest coll))
([-1 -2 3 5 6 -2 -1 4 -4 2 -1] (-2 3 5 6 -2 -1 4 -4 2 -1) (3 5 6 -2 -1 4 -4 2 -1) (5 6 -2 -1 4 -4 2 -1) (6 -2 -1 4 -4 2 -1) (-2 -1 4 -4 2 -1) (-1 4 -4 2 -1) (4 -4 2 -1) (-4 2 -1) (2 -1) (-1))
=> [3 5 6 -2 -1 4]
Run Code Online (Sandbox Code Playgroud)
有一个不错的库,叫做debux
(use '[debux.core])
(defn max-subseq-sum [coll]
(dbg (->> (take-while seq (iterate rest coll)) ; tails (1)
(mapcat #(reductions conj [] %)) ; inits (2)
(apply max-key #(reduce + %)))))
(max-subseq-sum [1 2 3])
dbg: (->> (take-while seq (iterate rest coll)) (mapcat (fn* [p1__1991#] (re ... =>
| (take-while seq (iterate rest coll)) =>
| ([1 2 3] (2 3) (3))
| (mapcat (fn* [p1__1991#] (reductions conj [] p1__1991#))) =>
| ([] [1] [1 2] [1 2 3] [] [2] [2 3] [] [3])
| (apply max-key (fn* [p1__1992#] (reduce + p1__1992#))) =>
| [1 2 3]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
594 次 |
最近记录: |