concept recur in category clojure

appears as: recur, recur, A recur
Clojure: The Essential Reference

This is an excerpt from Manning's book Clojure: The Essential Reference.

loop-recur is the most basic recursive construct in Clojure. loop is one of the possible targets to resume execution, while recur performs the controlled "jump" to transfer control to the inner-most loop or fn form (including defn, defn-, fn* and anonymous function literal #()). In general, Clojure allows 3 ways to recur:

1. A call to the function from within the function itself. No loop or recur is used in this case. The recursive call can appear anywhere, not just as last instruction, like in this example returning the n-th element in the Fibonacci series [65]:

(defn fib [n]
  (if (<= 0 n 1)
    n
    (+ (fib (- n 1)) (fib (- n 2)))))   ; #1

(map fib (range 10))
;; (0 1 1 2 3 5 8 13 21 34)

2. The recur special form invoked without a loop target will use the innermost containing function definition. Here’s is the same example re-written to avoid recurring twice:

(defn fib [a b cnt]
  (if (zero? cnt)
    b
    (recur (+ a b) a (dec cnt)))) ; #1

(map (partial fib 1 0) (range 10))
;; (0 1 1 2 3 5 8 13 21 34)

3. The recur special form invoked with a loop target will restart computation from the innermost loop form. The following is probably the most effective of the 3 fib versions presented so far. The presence of loop takes care of some initialization that doesn’t need to be outside the function and at the same time we are not recurring twice:

(defn fib [n]
  (loop [a 1 b 0 cnt n]               ; #1
    (if (zero? cnt)
      b
      (recur (+ a b) a (dec cnt)))))

(map fib (range 10))
;; (0 1 1 2 3 5 8 13 21 34)

These are the main differences between calling the function recursively and using the recur variants:

  • The compiler ensures that if recur is present, it needs to be in tail position. The compiler throws exception if recur is in not in tail position.
  • The compiler enables a special optimization when using recur that doesn’t consume the stack (see the tail-recursion section below for a detailed explanation).
  • The Joy of Clojure, Second Edition

    This is an excerpt from Manning's book The Joy of Clojure, Second Edition.

    Clojure has a special form called recur that’s specifically for tail recursion. The following function prints the integers from x to 1, counting backward:

    (defn print-down-from [x]   (when (pos? x) #1      (println x) #2      (recur (dec x)))) #3 #1 - Perform while still positive. #2 - Print the current x. #3 - Recurse with x minus 1. !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[]"} !@%STYLE%@!

    This is nearly identical to how you’d structure a while loop in an imperative language. One significant difference is that the value of x isn’t decremented somewhere in the body of the loop. Instead, a new value is calculated as a parameter to recur, which immediately does two things: rebinds x to the new value and returns control to the top of print-down-from.

    If the function has multiple arguments, the recur call must as well, just as if you were calling the function by name instead of using the recur special form. And just as with a function call, the expressions in the recur are evaluated in order first and only then bound to the function arguments simultaneously.

    We say that the recursive call is mundane[15] because it’s named explicitly rather than through mutual recursion or implicitly with the recur special form. Why is this a problem? The answer lies in what happens when you try to call pow with a large value:

    Unfortunately for Clojure, neither the Java Virtual Machine nor its bytecode provide generalized tail-call optimization facilities. Clojure does provide a tail call special form recur, but it only optimizes the case of a tail-recursive self call and not the generalized tail call. In the general case, there’s currently no way to reliably optimize (Clinger 1998) tail calls.

    There’s no technical reason why Clojure couldn’t automatically detect and optimize recursive tail calls—Scala does this—but there are valid reasons why Clojure doesn’t. First, because there’s no generalized TCO in the JVM, Clojure can only provide a subset of tail-call optimizations: the recursive case and the mutually recursive case (see the next section). By making recur an explicit optimization, Clojure doesn’t give the pretense of providing full TCO.

    Second, having recur as an explicit form allows the Clojure compiler to detect errors caused by an expected tail call being pushed out of the tail position. If you change gcd to always return an integer, then an exception is thrown because the recur call is pushed out of the tail position:

    (defn gcd [x y]
      (int
        (cond
           (> x y) (recur (- x y) y)
           (< x y) (recur x (- y x))
           :else x)))
    
    ; java.lang.UnsupportedOperationException: Can only recur from tail...

    With automatic recursive tail-call optimization, the addition of an outer int call wouldn’t necessarily trigger[19] an error condition (Wampler 2009). But Clojure enforces that a call to recur be in the tail position. This benefit will likely cause recur to live on, even should the JVM acquire TCO.