Search code examples
common-lisp

Named lambda in common lisp


I need to write a recursive helper function and do not need to give it global scope, but I need to reference it to achieve the recursion.

Emacs lisp has fset, which assigns to the function-cell of a symbol. What is the equivalent in common lisp?


Solution

  • I just found out that this is a idiom common enough to be in alexandria. From alexandria code:

    (defmacro named-lambda (name lambda-list &body body)
      "Expands into a lambda-expression within whose BODY NAME denotes the corresponding function."
      `(labels ((,name ,lambda-list ,@body))
     #',name))
    

    Here's a usage example:

    (let ((! ;; Everything can be a symbol :D
       ;; Definition here
       (named-lambda self (n)
             (case n
               (1 1)
               (otherwise (* n
                     (self (1- n)))))))) ;; Recurse here
      ;; How to call it
      (funcall ! 6))