I want to understand how works the following code that is designed for the problem: "Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements"
defn max-subseq-sum [coll]
(->> (take-while seq (iterate rest coll)) ; tails (1)
(mapcat #(reductions conj [] %)) ; inits (2)
(apply max-key #(reduce + %)))) ; max sum
so I'd like to see the output of forms (1), (2) and others. I can set breakpoints in Cursive but yet I don't know how to get these values. I have tried to define a locale variables, for example
(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])
But i still don't understand how to see d, for example
How to solve this problem?
A simple function that prints and returns its input can be inserted into the chain:
(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]
Or, if you want better tracking and don't mind a bit of bulk, you can use a macro that includes the expression in the printout:
(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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With