2

Why doesn't the following snippet of code print "1" to the console?

(loop
  [i 0]
  (println (if (= i 0) (recur 1) i)))

Instead, it throws clojure.lang.ExceptionInfo: Can't recur here at line 3 in the REPL. Are nested (recur..) statements like this not allowed in Clojure(Script)?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
George
  • 6,927
  • 4
  • 34
  • 67

3 Answers3

3

Correct, "nested recur statements" are not allowed in any Clojure dialect. The alternate behavior described in a comment (recur "halts and dismisses the execution of its parent statements") would work as an alternate language design choice, but would probably be a lot more confusing to read.

gfredericks
  • 1,312
  • 6
  • 11
0

In your code you try to print the result of (recur 1), which doesn't make sense. I think you probably meant to do (recur 1) if i==0, and print i otherwise, as follows:

(loop [i 0]
   (if (= i 0) (recur 1) (println i)))
Adi Levin
  • 5,165
  • 1
  • 17
  • 26
  • 1
    Yes, that's the natural way to do it. I was trying to figure out if `(recur ...)` halts and dismisses the execution of its parent statements. It doesn't seem like this is the case. – George Jan 23 '16 at 10:05
0

See Clojure: What exactly is tail position for recur? - you can only use recur from a "tail position" in Clojure. In this case, recur is not in a tail position because it is not the last thing to be evaluated in this function - the println would be evaluated after the call to recur.

Community
  • 1
  • 1
fzzfzzfzz
  • 1,248
  • 1
  • 12
  • 22