Clojure中调试线程宏 -> 或 ->>

6

我希望了解下面的代码如何工作,它是为以下问题而设计的:“给定一个整数序列,找到一个连续的子序列,使其元素的和最大”

defn max-subseq-sum [coll]
(->> (take-while seq (iterate rest coll)) ; tails (1)
   (mapcat #(reductions conj [] %)) ; inits   (2)
   (apply max-key #(reduce + %)))) ; max sum

我希望能看到表格(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])

但我仍然不明白如何查看d,例如

如何解决这个问题?


1
阅读 https://clojure.org/guides/repl/introduction 的全部内容,直到到达 https://clojure.org/guides/repl/enhancing_your_repl_workflow#debugging-tools-and-techniques,您将找到所有需要获取此类信息以及更多信息的技术! - marco.m
3个回答

11
可以将一个简单的函数插入到链式结构中,该函数打印并返回其输入内容:
(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]

如果你希望有更好的追踪效果并且不介意一点点冗长,你可以使用包含表达式的宏来打印输出:

(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]

7

有一个很棒的库叫做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]

1

我可以通过注入((fn [x] (println x) x))来实现。

(->> [1 2 3 4 5]
     (filter even?)
     ((fn [x] (println x) x))
     first)

显示

(2 4)
2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接