Clojure: Loop, Iteration

By Xah Lee. Date: . Last updated: .

Here's basic functions related to iteration:

(for [i (range 7)] (inc i)) ; (1 2 3 4 5 6 7)

clojure.core/range clojure.core/inc

Recursion

A function that calls itself is called recursion.

In a function definition, If a function calls itself as exit, then such recursion is called tail recursion or linear recursion.

Linear recursion is not nested in nature. You can think of it as “pass and forget”.

What is the difference between tail-recursion and non-tail-recursion?

Tail recursion can be trivially expressed as iteration or linear loop.

In programing languages, some programing language automatically compile tail-recursion into a iteration. (so that, it saves memory, avoiding stackoverflow, etc.) Scheme (programming language) is the language most famous for enforcing the tail-recursion optimization into its compiler, by spec.

Clojure supports recursion. That is, function can call itself.

Clojure also supports manual tail-recursion using recur. That is, the compiler optimize recursion that's linear into a iteration-like construct.

If the recursion is linear recursion, than you can call recur at the place you want to call function itself. The advantage is that there'll be no limit on recursion depth.

clojure.core/recur

clojure.core/loop