Programming Search⌘K

Conceptintro

Anonymous function

Also called lambda, lambda expression, lambda function, function literal, arrow function, function expression.

An anonymous function is a function with no name, written as an expression where the program needs it. Python lambda, JavaScript arrow functions, C# lambdas and Go function literals are examples.

Applies to
core-languages

Idea

An anonymous function is a function that has no name. The program writes it as an expression, often as the argument of another function. Wikipedia gives the definition: "In computer programming, an anonymous function (function literal, lambda function, or block) is a function definition that is not bound to an identifier."1

words = ["house", "car", "bike"]
print(sorted(words, key=lambda w: len(w)))


def length(w):
    return len(w)


print(sorted(words, key=length))
Output
['car', 'bike', 'house']
['car', 'bike', 'house']

The two calls do the same work. The first call gives sorted an anonymous function. The second call gives it the named function length. SICP says that a procedure made with lambda "is just as much a procedure as one that is created using define. The only difference is that it has not been associated with any name in the environment."2

How it works

  1. An expression makes a function. The anonymous function is an expression, so it can be in any place where a value can be: an argument, a variable or a return value. In Python, "The expression lambda parameters: expression yields a function object."3
  2. The body. Some languages allow only one expression in the body. Others allow a block of statements. In Java, the body "consists of a single expression or a statement block"4.
  3. The types. Many statically typed languages get the types of the parameters from the place where the function is used. In TypeScript, "When a function appears in a place where TypeScript can determine how it’s going to be called, the parameters of that function are automatically given types."5
  4. The captured variables. An anonymous function can use the variables around it. Then it is a closure. In Go, "Function literals are closures: they may refer to variables declared in a surrounding function."6

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CAbsent
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNativeKotlin has lambda expressions such as { x -> x * x } and anonymous functions that start with the keyword fun. No example file exists because kotlinc is not installed.
SQLDoes not applyStandard SQL has no function values, so it has no anonymous functions.
BashAbsent
PowerShellNativeA script block such as { param($x) $x * $x } is an anonymous piece of code that a program can store and call with the & operator. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is a markup language and has no functions.
CSSDoes not applyCSS has no way to define a function.
Regular expressionsDoes not applyA regular expression has no functions.
  • Python. The lambda expression. "Lambda expressions (sometimes called lambda forms) are used to create anonymous functions."3 The body is one expression: lambda functions "are syntactically restricted to a single expression"7.
  • JavaScript. Function expressions such as function (x) { return x * x; } and arrow functions such as (x) => x * x. "An arrow function expression is a compact alternative to a traditional function expression, with some semantic differences and deliberate limitations in usage"8.
  • TypeScript. The same forms as JavaScript, with optional type annotations. The parameters get their types from the context5.
  • Java. Lambda expressions such as x -> x * x. "Lambda expressions let you express instances of single-method classes more compactly."4
  • C#. Lambda expressions such as x => x * x. "Use a lambda expression to create an anonymous function."9 A static lambda "can't capture local variables or instance state from enclosing scopes"9.
  • C. C has no anonymous functions. "A function is a C language construct that associates a compound statement (the function body) with an identifier (the function name)."10 A C program passes a pointer to a named function.
  • C++. Lambda expressions such as [](int x) { return x * x; }. A lambda "Constructs a closure (an unnamed function object capable of capturing variables in scope)."11
  • Go. Function literals such as func(x int) int { return x * x }. "A function literal represents an anonymous function."6
  • Rust. Closures such as |x| x * x. "Rust’s closures are anonymous functions you can save in a variable or pass as arguments to other functions."12 "Closures don’t usually require you to annotate the types of the parameters or the return value like fn functions do."12
  • Bash. Bash has no anonymous functions. The syntax fname () compound-command "defines a shell function named fname"13, so every Bash function has a name.
PythonGitHub
words = ["house", "car", "bike"]
print(*sorted(words, key=lambda w: len(w)))

print(*map(lambda x: x * x, [1, 2, 3]))

n = 5
print((lambda x: x + n)(10))
Output
car bike house
1 4 9
15
  • Verdict: native. lambda w: len(w) and lambda x: x * x are anonymous functions. The last lambda uses the variable n from the code around it.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> words = {"house", "car", "bike"};
    std::sort(words.begin(), words.end(),
              [](const std::string& a, const std::string& b) { return a.size() < b.size(); });
    std::cout << words[0] << ' ' << words[1] << ' ' << words[2] << '\n';

    std::vector<int> nums = {1, 2, 3};
    std::transform(nums.begin(), nums.end(), nums.begin(), [](int x) { return x * x; });
    std::cout << nums[0] << ' ' << nums[1] << ' ' << nums[2] << '\n';

    int n = 5;
    auto add = [n](int x) { return x + n; };
    std::cout << add(10) << '\n';
}
Output
car bike house
1 4 9
15
  • Verdict: native. The lambdas start with a capture list. [] captures nothing, and [n] captures n by value.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.function.IntUnaryOperator;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>(List.of("house", "car", "bike"));
        words.sort((a, b) -> Integer.compare(a.length(), b.length()));
        System.out.println(String.join(" ", words));

        String squares = List.of(1, 2, 3).stream()
                .map(x -> String.valueOf(x * x))
                .collect(Collectors.joining(" "));
        System.out.println(squares);

        int n = 5;
        IntUnaryOperator add = x -> x + n;
        System.out.println(add.applyAsInt(10));
    }
}
Output
car bike house
1 4 9
15
  • Verdict: native. The lambdas (a, b) -> ..., x -> ... and x -> x + n are anonymous functions. A lambda can use a local variable such as n only if the variable does not change after its assignment.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int by_length(const void *a, const void *b) {
    size_t la = strlen(*(const char *const *)a);
    size_t lb = strlen(*(const char *const *)b);
    return (la > lb) - (la < lb);
}

static int square(int x) { return x * x; }

static void map(int (*f)(int), int *xs, size_t n) {
    for (size_t i = 0; i < n; i++) {
        xs[i] = f(xs[i]);
    }
}

struct adder {
    int n;
};

static int adder_call(const struct adder *a, int x) { return x + a->n; }

int main(void) {
    const char *words[] = {"house", "car", "bike"};
    qsort(words, 3, sizeof words[0], by_length);
    printf("%s %s %s\n", words[0], words[1], words[2]);

    int nums[] = {1, 2, 3};
    map(square, nums, 3);
    printf("%d %d %d\n", nums[0], nums[1], nums[2]);

    struct adder add = {5};
    printf("%d\n", adder_call(&add, 10));
    return 0;
}
Output
car bike house
1 4 9
15
  • Verdict: absent. C has no anonymous functions. The program defines named functions and passes pointers to them. The adder is a struct that holds n and a function that takes the struct.
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var words = new List<string> { "house", "car", "bike" };
        words.Sort((a, b) => a.Length.CompareTo(b.Length));
        Console.WriteLine(string.Join(" ", words));

        Console.WriteLine(string.Join(" ", new[] { 1, 2, 3 }.Select(x => x * x)));

        int n = 5;
        Func<int, int> add = x => x + n;
        Console.WriteLine(add(10));
    }
}
Output
car bike house
1 4 9
15
  • Verdict: native. The lambdas use the operator =>. The lambda add captures the local variable n.
JavaScriptGitHub
const words = ["house", "car", "bike"];
console.log([...words].sort((a, b) => a.length - b.length).join(" "));

console.log(
  [1, 2, 3]
    .map(function (x) {
      return x * x;
    })
    .join(" "),
);

const n = 5;
const add = (x) => x + n;
console.log(add(10));
Output
car bike house
1 4 9
15
  • Verdict: native. The sort uses an arrow function, and the map uses a function expression. The arrow function add uses the constant n.
TypeScriptGitHub
const words: string[] = ["house", "car", "bike"];
console.log([...words].sort((a, b) => a.length - b.length).join(" "));

console.log([1, 2, 3].map((x) => x * x).join(" "));

const n = 5;
const add = (x: number): number => x + n;
console.log(add(10));
Output
car bike house
1 4 9
15
  • Verdict: native. The arrow functions have no type annotations. TypeScript gets the types of a, b and x from the calls to sort and map.
package main

import (
	"fmt"
	"sort"
)

func main() {
	words := []string{"house", "car", "bike"}
	sort.Slice(words, func(i, j int) bool { return len(words[i]) < len(words[j]) })
	fmt.Println(words[0], words[1], words[2])

	nums := []int{1, 2, 3}
	square := func(x int) int { return x * x }
	for i, x := range nums {
		nums[i] = square(x)
	}
	fmt.Println(nums[0], nums[1], nums[2])

	n := 5
	add := func(x int) int { return x + n }
	fmt.Println(add(10))
}
Output
car bike house
1 4 9
15
  • Verdict: native. Function literals have the full signature with types. The literal add refers to n from main.
RustGitHub
fn main() {
    let mut words = vec!["house", "car", "bike"];
    words.sort_by_key(|w| w.len());
    println!("{}", words.join(" "));

    let squares: Vec<String> = [1, 2, 3].iter().map(|x| (x * x).to_string()).collect();
    println!("{}", squares.join(" "));

    let n = 5;
    let add = |x| x + n;
    println!("{}", add(10));
}
Output
car bike house
1 4 9
15
  • Verdict: native. Closures such as |w| w.len() need no type annotations. The closure add borrows n.
BashGitHub
square() {
  echo $(($1 * $1))
}

map() {
  local f=$1 x out=()
  shift
  for x in "$@"; do
    out+=("$("$f" "$x")")
  done
  echo "${out[@]}"
}

by_length() {
  local w
  for w in "$@"; do
    echo "${#w} $w"
  done | sort -n | cut -d' ' -f2 | paste -sd' ' -
}

by_length house car bike
map square 1 2 3

n=5
add() {
  echo $(($1 + n))
}
add 10
Output
car bike house
1 4 9
15
  • Verdict: absent. Every Bash function has a name. The program passes the name square to map, and add reads the global variable n.
  • Names. Wikipedia lists the names "function literal, lambda function, or block"1. "In several programming languages, anonymous functions are introduced using the keyword lambda, and anonymous functions are often referred to as lambdas or lambda abstractions."1
  • Expression body or block body. Python allows only an expression7. JavaScript, Java and C# allow an expression body or a block body849. C# calls the two forms an expression lambda and a statement lambda9.
  • Closures. An anonymous function that uses outer variables is a closure. Go function literals6, C++ lambdas11 and Rust closures12 can capture variables. See Closure.
  • First-class functions. An anonymous function is only useful when functions are values. See First-class function and Higher-order function.
  • Local functions. A named function inside another function is the other way to make a small helper. See Local and nested functions.

Pitfalls

An object literal in an arrow function body

In JavaScript, a brace after => starts a block, not an object. MDN says that (params) => { object: literal } "does not work as expected"8:

This code runs but gives a wrong answer on purpose.

const wrap = (value) => { value: value };
console.log(wrap(5));
Output
undefined

The body is a block with the label value and the expression value. The block has no return, so the call gives undefined. MDN gives the fix: "wrap the object literal in parentheses"8. Write (value) => ({ value: value }).

A Python lambda holds one expression

A Python lambda cannot hold an assignment, a loop or a return. "Note that functions created with lambda expressions cannot contain statements or annotations."3 When the code needs statements, write a named function with def.

An arrow function is not a method

Arrow functions "don't have their own bindings to this, arguments, or super, and should not be used as methods"8. An arrow function in an object literal cannot read the object through this. Use the method syntax or a function expression for methods.

Cost

An anonymous function costs the same as a named function with the same body. The Python tutorial says that lambda functions "are just syntactic sugar for a normal function definition"7. An anonymous function that captures variables costs the same as any other closure.

History

"Anonymous functions originate in the work of Alonzo Church in his invention of the lambda calculus, in which all functions are anonymous, in 1936, before electronic computers."1 "Anonymous functions have been a feature of programming languages since Lisp in 1958"1. Lisp took the keyword lambda from the notation of the lambda calculus2. SICP says: "It would be clearer and less intimidating to people learning Lisp if a name more obvious than lambda, such as make-procedure, were used. But the convention is firmly entrenched."2

References

  1. Anonymous function, Wikipedia, the introduction; Names
  2. Structure and Interpretation of Computer Programs, second edition, Abelson and Sussman, 1.3.2 Constructing Procedures Using Lambda, footnote 53
  3. Expressions, The Python Language Reference, 6.14 Lambdas
  4. Lambda Expressions, The Java Tutorials, the introduction; Syntax of Lambda Expressions
  5. Everyday Types, The TypeScript Handbook, Anonymous Functions
  6. The Go Programming Language Specification, Function literals
  7. More Control Flow Tools, The Python Tutorial, 4.9.6 Lambda Expressions
  8. Arrow function expressions, MDN Web Docs, the introduction; Function body
  9. Lambda expressions and anonymous functions, C# language reference, the introduction; Capture of outer variables and variable scope in lambda expressions
  10. Functions, C reference, cppreference.com, the introduction
  11. Lambda expressions (since C++11), C++ reference, cppreference.com, the introduction
  12. Closures, The Rust Programming Language, the introduction; Inferring and Annotating Closure Types
  13. Shell Functions, Bash Reference Manual, 3.3 Shell Functions

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/M0DRR8/text.yaml