Recur form without Accumulator

Hello ClojureVerse

I am a beginner to clojure. In the recursion examples that I have seen, any function or loop employing the recur form always takes two or more parameters with one parameter being the accumulator.

Am I correct in thinking that the accumulator is required for functions/loops with the recur form because clojure wants the recur call to be the tail call?

Is there a way to do recursion with the recur form in clojure without using an accumulator?

You can use recur with no arguments, but in general you want to have a way to break out of execution (a “base case” for your recursive function). There may be cases where you would want to loop until some external event happen, and you could use side-effects for this, but in general it’s best to pass some argument to recur.
See the screenie below for a horribly contrived example :smiley:

Hello and welcome!

It’s true that Clojure expects recur calls in tail positions, but an accumulator is not strictly necessary.

Just as @mvarela wrote, you are free to use recur without any arguments at all.
The implementation of while is a good example. It’s useful if the condition of your loop depends on some external side-effects.

In Clojure we tend to use an explicit accumulator because our data structures are immutable. The same applies to other languages based on immutable data structures, such as Erlang or Haskell.

When we accumulate results of recursion, we don’t modify a mutable accumulator. Instead, we create a new one, derived from the existing one. The implementation of Clojure’s persistent data structures makes it less expensive than it sounds.

If our data were mutable, we could modify them in place instead of carrying over an explicit accumulator. Parts of Clojure’s standard library are implemented that way using transients. It’s not something we resort to often outside of hotspots of our applications.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.