[Clojure] – What is tail recursion ?

As in Clojure and functional programming we don’t have recursion, this is the resource used to treat this situation.

Why we don’t have recursion as the imperative languages?

Because one function calls another and so on. The compiler will stacking the results and calls and so you find a memory problem. To resolve this issue we have the tail recursion.

How to handle recursion ?

The compiler is smart enough to avoid stacking of these calls when using a syntax of tail recursion. In Clojure use “recur” syntax to set the call is a tail recursive.

Example :

(defn end [] (print "End"))

(defn counter[num]
    (if (= num 0)
        (end)
        (do
            (print num)
            (recur (dec num))
        )
    )
)

(counter 4)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s