Search code examples
emacsiterationlet

`let loop` (named let) alternative in emacs lisp


In Scheme there's a let loop construct which is essentially the same as creating a self-recursive lambda in-place (aka 'named let'). For example, a factorial of 6 can be written as:

(let fact ([x 6])
  (if (< 1 x)
      (* x (fact (- x 1)))
      x))

The question is: is there any alternative in elisp. And if there exists one, does it perform tail recursion optimization where possible?


Solution

  • You're looking for cl-labels. See https://stackoverflow.com/a/39564067/324105 for a very similar example to your code (along with some other related facilities).

    See also: C-hig (cl)Function Bindings

    does it perform tail recursion optimization where possible?

    No, there is no TCO in Emacs Lisp, other than in the work-in-progress native-compilation feature (where it is currently disabled by default, so presumably not considered ready for general use; but even if it were, it would be a risk to rely upon it other than for personal use, as it's not safe to assume that other people will also be running native-compiled code).

    For this reason, arbitrary recursion is generally eschewed by elisp programmers in favour of iterative techniques.