I am a newbie in clojure and was implementing Kadane's algorithm. The quality of the code is pretty bad and which is fine as i want to write the bad code first and then gradually improve. Somehow my for loop is not executing. Please guide
I have tried various combinations of prints but failed hence i come to you
(defn max-contigous-sub-array [list]
(let [local-sum (atom (first list))
global-sum (atom (first list))]
(doseq [x (rest list)]
(do
(reset! local-sum (max x (+ @local-sum x)))
(if (> @local-sum @global-sum)
(reset! global-sum @local-sum))))
@global-sum))
The for
function in clojure is not an imperative loop but a function for producing lazily-generated list comprehensions. For your case, you should use the doseq
loop.
https://clojuredocs.org/clojure.core/for
https://clojuredocs.org/clojure.core/doseq
The reason your current loop is never being executed is because you're never doing anything with the lazy sequence returned by the for
function, and so the lazy seq is never evaluated.