Disclaimer: I'm learning clojure.
This is the simple example I'm trying to run:
(ns ClojureTest.core)
(let [input (read-line)]
;if user input = "x"
(if (= "x" input)
;stop accepting input
(println "Exit")
;else output the input and continue accepting input
(
(println input)
(recur)
)
)
)
Now I'm getting this error, which I guess makes sense, because I'm unfamiliar with syntax:
Exception in thread "main" java.lang.UnsupportedOperationException: Can only recur from tail position, compiling:(ClojureTest/core.clj:8:7)
How do I fix this?
Side questions:
In this particular case, you're missing a do
in the "else" clause of the if
:
(do
(println input)
(recur))
Without the do
, you've got ((println input) (recur))
, which looks like a function call with the return value of (println input)
being the function to call and (recur)
being the argument expression and so, not in tail position.
(Clearly (println input)
would return nil
and attempting to call that as a function would throw a NullPointerException
, but this is irrelevant here -- it would be a runtime error, whereas the recur
-not-in-tail-position problem is detectable at compile time.)