ELisp: Lambda Function

By Xah Lee. Date: . Last updated: .

What is Lambda Function

A function can be defined by keyword lambda.

Lambda is also know as anonymous function. Lambda 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 interactive_clause_optional body)

example:

(lambda (x)
   (1+ x))

Longer lambda can use let binding to declare local variables. [see ELisp: 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 lambda to a value:

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

Lambda function is often used with mapcar. [see ELisp: Map, Iteration]

;; take the 2nd element of each
(mapcar
 (lambda (x) (aref x 1))
 [[1 2] [3 4] [5 6]]
 )
;; (2 4 6)

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

Name a 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.

;; -*- coding: utf-8; lexical-binding: t; -*-

(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.

Lambda Expressions (ELISP Manual)

Emacs Lisp Function