Emacs Lisp: Lambda (Anonymous Function)

By Xah Lee. Date: . Last updated: .

What is Lambda Function

A function can be defined by lambda.

Lambda function is also know as anonymous function. Lambda function is just like function defined by defun , except it's not named. Lambda function is typically only used once.

Lambda Syntax

(lambda (params) doc_string_optional body)

example:

(lambda (x)
   "simple function to add 1"
   (1+ x))

Longer lambda can use let binding to declare local variables. [see Emacs Lisp: Variable]

(lambda (x)
  "toy lambda example. given x, return (list 1 2 3 x)"
  (let (a b c)
    (setq a 1)
    (setq b 2)
    (setq c 3)
    (list a b c x)))

Apply the Lambda to Value

apply the lambda to a value:

((lambda (x)
   "simple function to add 1"
   (1+ x)) 3)
;; 4

Lambda function is often used with mapcar or mapc. Apply the lambda to a list:

(mapcar
 (lambda (x)
   "simple function to add 1"
   (1+ x))
 (list 1 2 3))
;; (2 3 4)

Lambda function of 2 parameters:

define a lambda function of 2 parameters:

(lambda (x y) "add 2 numbers"
   (+ x y))

apply the lambda to arguments:

((lambda (x y)
   (+ x y))
 3 4 )
;; 7

Nested Lambda

lambda can be nested:

((lambda (x)
   ((lambda (x)
      (1+ x)) x)) 3)
;; 4

Set a Name to Lambda Function

you can use fset to give it a name.

(fset 'f1 (lambda (y) "add 1 to arg" (1+ y)))

(f1 2)
;; 3

Defining Inner Function?

I haven't figured out how to define a inner function.

if the variable is a local variable, fset will make it global, not local function as you might want for inner function.

(defun f1 (x)
  "DOCSTRING"
  (interactive)
  (let (f2)
    (fset 'f2 (lambda (y) "add 1 to arg" (1+ y)))
    (f2 x)))

(f1 2)
;; 3

(fboundp 'f2) ; t

(f2 2)
;; 3

Note: emacs lisp does not let you easily assign a lambda function to a local variable.

(info "(elisp) Lambda Expressions")

Lisp Basics

Emacs Lisp Function

ErgoEmacs mascot-s276x226
Buy Xah Emacs Tutorial

Lisp Basics

Basics

Lisp Data Structure

Function

Lisp Symbol

Lisp Misc

Working with Elisp