Why does this bit of Clojure code:
user=> (map (constantly (println "Loop it.")) (range 0 3))
Yield this output:
Loop it.
(nil nil nil)
I’d expect it to print “Loop it” three times as a side effect of evaluating the function three times.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
constantlydoesn’t evaluate its argument multiple times. It’s a function, not a macro, so the argument is evaluated exactly once beforeconstantlyruns. Allconstantlydoes is it takes its (evaluated) argument and returns a function that returns the given value every time it’s called (without re-evaluating anything since, as I said, the argument is evaluated already beforeconstantlyeven runs).If all you want to do is to call
(println "Loop it")for every element in the range, you should pass that in as the function to map instead ofconstantly. Note that you’ll actually have to pass it in as a function, not an evaluated expression.