clojure - Why does y = 0 when I run println? -
how come when run
(def y 0) (doseq [x (range 1000)] (if (or (= (mod x 3) 0) (= (mod x 5) 0)) (+ y x))) (println y)
it prints 0
if no addition has taken place but
(doseq [x (range 1000)] (if (or (= (mod x 3) 0) (= (mod x 5) 0)) (println x)))
will print out of corresponding numbers match conditions?
in clojure, values immutable. y
is, , 0 of eternity. (+ y 1)
1, , 1. (+ y 1)
not change value of y
, evalutates result of adding 1 immutable value y
.
try this:
(println (reduce (fn [y x] (if (or (= (mod x 3) 0) (= (mod x 5) 0)) (+ y x) y)) 0 (range 1000)))
here, build y
on time reducing on range in question. if match condition, add next value (x
). if don't match condition, return y.
look reduce
function.
note: there typos, wrote on phone
Comments
Post a Comment