0

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?

1 Answer 1

2

Your code is not correct. It will go into infinite loop because a number is either even or odd, so on each iteration recur will 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 recur when 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 loop and recur, using standard functions like map, filter and reduce (or for macro).

Sign up to request clarification or add additional context in comments.

5 Comments

ah yes I overlooked that, the function was wrong. I have another now that applies the forms in an atom. However it does not continue the process for some reason, I was thinking that I use swap! two times: (defn henk [n] (def a (atom n)) (while (odd? @a) (println a)(swap! a * 3)(swap! a + 1) )
could it be that useing (swap! a) 2x after eachother that it gives some sort of error that stopts the script?
Using atom is not a good idea at all, and also def is not intended to be used inside forms, it is top-level macro (you should use let for local bindings). The code on the following link is idiomatic version of your code: gist.github.com/3886160
I did try to make it with recur however I every time I used it, i couldn't make it to loop. It only does 1 full loop and doesn't continue. Is there a way to make the looping longer?
If it does not recur, then it has fulfilled the exit condition. In case of the henk function that means that the number has become even. In fact, the linear transformation 3*x+1 always yields even result for odd x, because when you multiply some odd number by odd number (3 in this case) you get another odd number, and odd number plus one is even.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.