Pergunta

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:

  1. When I click "run" in eclipse (as I would do with Java) I get not only the console opened but this "REPL" window. Why is it necessary and what does it do?
  2. When I click "run" it takes quite a few seconds to launch the app. Is there a way to make it faster?
  3. When I need to edit the code and relaunch the app I'm getting this message: "The selection cannot be launched, and there are no recent launches". What is that and why wouldn't it let me relaunch my code? If I wait a while I can launch it again.
Foi útil?

Solução

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.)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top