recur
While for
is somewhat like a loop,
recur
is a real loop in Clojure.
recur
represents such a remarkable idea that we might even say, “this is Clojure.”
If you have a programming background, you may have heard of tail recursion,
which is a major feature of functional languages.
This recur
special form is the one that implements tail recursion.
As the words “tail recursion” indicate, recur
must be called in the tail position.
In other words, recur
must be the last thing to be evaluated.
The syntax of the recur
macro is: (recur exprs*)
Look at these simple examples:
Even though we can write code without recur
, the use of recur
is strongly recommended in Clojure
because of tail-call optimization (TCO).
Compare a recursive sum-up function and a sum-up-with-recur function that uses recur
.
The recursive call raises StackOverflowError when summing up to 10000.
On the other hand, recur
can sum up even 100000.
This is why tail-call optimization (TCO) works effectively.
In every computer language, we can write recursive calls. However, recursion with TCO is a Clojure-specific feature. With TCO, Clojure is good at processing a huge list.
ClojureDocs
Clojure.org, Special Forms, recur
http://clojure.org/special_forms#Special%20Forms–(recur%20exprs*)
Clojure from the ground up: macros, Recursion
http://aphyr.com/posts/305-clojure-from-the-ground-up-macros
Clojure for the Brave and True, Functional Programming, 2.1 Recursion instead of for/while
http://www.braveclojure.com/functional-programming/#2_1__Recursion_instead_of_for_while
GetClojure