DEV Community

Discussion on: Share a code snippet in any programming language and describe what's going on

Collapse
 
wsgac profile image
Wojciech S. Gac

My implementation of factorial in Emacs Lisp

(defun factorial (n)
  "Compute the factorial of N in a tail-recursive manner."
  (labels ((tail-factorial (n acc)
        (if (zerop n)
            acc
          (tail-factorial (1- n) (* n acc)))))
    (tail-factorial n 1)))
Enter fullscreen mode Exit fullscreen mode

This is a standard way to implement factorial using tail recursion. defun marks the beginning of function definition. Then goes the name (factorial) and list of arguments ((n)). After that we have an optional docstring (the good part about Emacs being self-documenting has long been the fact that docstrings become incorporated into an online help system - this is no longer surprising in programming languages, but used to be rare). labels introduces a local function - only visible within the enclosing scope. It's actually this inner function that is tail-recursive - the parameter acc is used to weave the partial result through the sequence of recursive calls, to be returned at the bottom. By using tail recursion (provided our language supports it) leverage so-called TCO (Tail Call Optimization) to avoid building up a stack with recursive calls. Finally, we call our inner, tail-recursive function on the original parameter n and initialize acc to 1. This way we get the desired behavior of 0! = 1.