The difference between FOR and DOSEQ in clojure

Asked

Viewed 37 times

0

What difference between for and doseq?

I wrote a program, which returns me the highest value within the parameters informed. Note: I know that there is a function max and max-key, but I don’t want to use them because I want to train the language.

Example:

Using doseq, works.

(defn valorMaximo [& num]
  (let [x (atom (first num))]
    (doseq [i num] (when (> i @x) (reset! x i)) ) @x))

Using for, doesn’t work.

(defn valorMaximo2 [& num]
  (let [x (atom (first num))]
    (for [i num :when (> i @x)] (reset! x i)) @x))

1 answer

0


The problem is that the body of for is not evaluated until necessary. It is like a python generating expression.

Like the for does not perform your body until it is forced, and you are not forcing its execution, side effects do not happen.

Anyway, you shouldn’t be using atom. This is a case for reduce:

(defn valor-maximo [& num]
  (when-not (empty? num)
    (reduce (fn [max-atual n]
              (if (> n max-atual)
                n
                max-atual))
            num)))
  • First, thank you, I had seen the function reduce but had not understood its functioning. but now it was very clear, thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.