Lisp - Recursion



Recursion, is one of the core concept of a function programming language. LISP, being a functional programming language, prefers recursions over iterative solutions. In this chapter, let's delve into the concept of recursion and its usage in LISP.

What is Recursion

  • Recursion is a programming technique where a function calls itself within its own definition.

  • Purpose of recursion is to solve problem by breaking it into sub-problems.

  • As a function calls itself, there must be a base case to break the infinite calling. Base case is to break the recursive calls.

Why Recursion

  • In LISP, functions are first class citizens, thus recursion is a natural fit here.

  • Problems can be expressed easily in recursive form.

  • As LISP is primarily using list processing capabilties, recursion is well suited for traversing and manipulating lists.

Key Components of Recursion

  • Base Case − A condition to stop the recursive call. It is generally the simplest case returning a result.

  • Recursive Case − A condition to call the function itself. Next function should reduce the scope and should bring the problem closer to the base case.

Example - Factorial using Recursion

Following is an example of a factorial function using recursive techniques.

main.lisp

; define a function to compute factorial
(defun factorial (n)
  (if (= n 0) ; base case
      1
      (* n (factorial (- n 1))))) ; recursive call
      
; call factorial of 5; evaluates to 120
(print (factorial 5))

Output

When you execute the code, it returns the following result −

120

Explanation

  • (= n 0)− This is a base case. If n is 0, 1 is returned as factorial of 0 is 1.

  • (* n (factorial (- n 1)))− This is a recursive case. Here we're multiplying factorial of n-1 with n. This call continues until n reaches 0.

While using recursion, special care is required as stack overflow conditions is easy to occur and hard to debug. And when used appropriately, a recursive code is quite elegant and concise.

Advertisements