I am trying to make a continues loop that contains multiple when’s. What I currently have is this:
(defn test [n]
(loop [x n]
(when (> x 1)
(println x))
(when (even? x)
(recur (- x 1))
(println x))
(when (odd? x)
(recur (+ x 2))
(println x))
)
)
Is there a possible way to do this in clojure?
Your code is not correct. It will go into infinite loop because a number is either even or odd, so on each iteration
recurwill always be called. Also, it is not obvious what exactly you want to do; if you explain your problem, it will be possible to give more definitive answer.You have to define an exit condition first – what do you want this function to return? Then you have to structure your loop in such a way that it will not call
recurwhen exit condition is met. In this case the function will eventually return something.It is also highly possible that you can do what you want without even resorting to low-level primitives like
loopandrecur, using standard functions likemap,filterandreduce(orformacro).