Recursion in Clojure

Our example demonstrates recursive functions in Clojure. Here’s a classic factorial implementation:

(ns recursion-example.core
  (:gen-class))

(defn fact [n]
  (if (zero? n)
    1
    (* n (fact (dec n)))))

(defn -main []
  (println (fact 7))

  (let [fib (fn fib [n]
              (if (< n 2)
                n
                (+ (fib (- n 1)) (fib (- n 2)))))]
    (println (fib 7))))

This fact function calls itself until it reaches the base case of (fact 0).

In Clojure, we don’t need to explicitly declare recursive functions before defining them, as we do with closures in some other languages. Instead, we can use the fn special form with a name to create a recursive anonymous function.

The fib function is defined as a local binding using let. It’s a recursive function that calculates the nth Fibonacci number.

To run this program, save it in a file named recursion_example.clj and use the following command:

$ clj recursion_example.clj
5040
13

In Clojure, recursion is a fundamental concept, and the language is designed to handle recursive calls efficiently through tail-call optimization in many cases. However, for better performance with recursive algorithms like Fibonacci, you might want to consider using lazy sequences or memoization in real-world applications.

Markdown format suitable for Hugo