My third IPM was a success. I have a few things I need to tighten up on, but it seems like it is forward progress. One of the big critiques I received was not being as educational as I should in these blog posts, which is valid. I definitely go about my daily life, which I should still do, but don’t go into detail about new concepts I’ve learned.

On that note today I’d like to go into a little more detail about recursion in Clojure. Recursion is a very fundamental concept in Clojure. It allows functions to call upon themselves to solve a problem. Recursion is the primary mechanism for iterating and looping in Clojure as opposed to a for/while loop in other languages. Clojure does still have a loop function, but it is less efficient than recursion and shouldn’t be your first option out of the two.

You can call a function recursively at any time by calling the functions name inside the function and providing the required arguments. If you are going to call the function recursively at the tail of the function it is important to know about the “recur” special form. “recur” is used to make a recursive call that reuses the current stack frame, preventing stack overflow.

Some of the advantages of recursion over traditional loop is the elegance of it. It is much more concise and easier to understand compared to loops. Recursion also works well with immutable data structures (which is what majority of Clojure is made up of if not all). Also, even though the Java Virtual Machine (in which Clojure runs on) does not natively support tail call optimization, “recur” has a mechanism to achieve it efficiently.

Important things to remember:

  • Make sure that you always have a clear base case to prevent infinite recursion.

  • Use “recur” for tail-recursive functions to avoid stack overflow.

  • Know that recursion is not always the most efficient option. Often times other functional constructs (such as “reduce”, “map”, or “filter” ) may be more appropriate.

Overall, recursion is a powerful tool that is an expressive and elegant solution to many programming problems.