Anonymous function

from Wikipedia, the free encyclopedia

An anonymous function ( function literal , lambda function , or lambda expression ) is a function definition that is not tied to an identifier. An anonymous function that gets access to its creation context is called a closure . Anonymous functions are often passed as arguments to higher-order functions , or used to construct the result of a higher-order function that a function must return. When a function is only used in one place and is of limited scope, an anonymous function can be syntactically simpler than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages ​​with first-class functions , where they fulfill the same role for the function type as literals for other data types .

Anonymous functions were originally coined by Alonzo Church with his invention of the lambda calculus in 1936, in which all functions are anonymous. Anonymous functions have been a feature of programming languages since Lisp in 1958 , and an increasing number of modern programming languages ​​support anonymous functions.

Named functions

In contrast to an anonymous function, a named function is given a unique identifier when it is declared , under which it is then addressed. The name of the function is used by the compiler or the runtime system to identify the function definition with the help of the symbol table or a dynamic method and to execute the code stored there.

Example in JavaScript

function identifier() {
    console.log("Hello, world!");
}

identifier();

Example in C

#include <stdio.h>

void identifier() {
    puts("Hello, world!");
}

int main() {
    identifier();
}

Examples

Common Lisp

(lambda (x) (* x 2))

To use this function, which doubles a value, in the same turn, the function can be applied directly with an argument:

((lambda (x) (* x 2)) 5)

What is 10returned on.

(defun myFilter (predicate container)
    (cond ((null container) nil)
        ((if (funcall predicate (car container))
            (cons (car container) (myFilter predicate (cdr container)))
            (myFilter predicate (cdr container))))))

(print (myFilter (lambda (value) (= (mod value 2) 0))' (0 1 2 3 4 5 6 7 8 9)))

C ++

Lambda expressions offer semantically similar possibilities as the related concept of function pointers . In C ++, anonymous functions can be defined as follows:

[capture]<template>(parameter) -> type { body }

  • capture: Transfer of the specified symbols into the scope of the lambda expression
  • template: List of the template parameters
  • parameter: List of transfer parameters
  • type: return type
  • body: functional body
#include <functional>
#include <iostream>
#include <vector>

using namespace std;

vector<int> myFilter(function<bool(int)> predicate, const vector<int> &container) {
    auto sieve = vector<int>();
    sieve.reserve(container.size());

    for (int element: container)
        if (predicate(element))
            sieve.push_back(element);

    return sieve;
}

int main() {
    vector<int> container = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    auto sieve = myFilter([](int value) { return value % 2 == 0; }, container);
        
    for (int element: sieve)
        cout << element << " ";

    return 0;
}

C #

using System;
using System.Collections.Generic;

delegate bool Function(int value);

class Program {
    static List<int> myFilter(Function predicate, List<int> container) {
        var sieve = new List<int>();
        sieve.Capacity = container.Count;

        foreach (var element in container)
            if (predicate(element))
                sieve.Add(element);

        return sieve;
    }

    public static void Main(string[] args) {
        var container = new List<int>() {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        var sieve = myFilter(value => value % 2 == 0, container);

        foreach (int element in sieve)
            Console.Write(element + " ");
    }
}

Haskell

myFilter predicate container = [element | element <- container, predicate element]

main = print $ myFilter (\value -> mod value 2 == 0) [0..9]

Java

In Java, anonymous inner classes used to be used for this purpose . From version 8 so-called lambda expressions are available.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.IntPredicate;
import java.util.List;

class Main {
    static List<Integer> myFilter(IntPredicate predicate, List<Integer> container) {
        var sieve = new ArrayList<Integer>();

        for (Integer element: container)
            if (predicate.test(element))
                sieve.add(element);

        return sieve;
    }

    public static void main(String[] args) {
        var container = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
        var sieve = myFilter(value -> value % 2 == 0, container);

        for (var element: sieve)
            System.out.print(element + " ");
    }
}

JavaScript

function myFilter(predicate, container) {
    let sieve = [];

    for (let element of container)
        if (predicate(element))
            sieve.push(element);

    return sieve;
}

let container = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(myFilter(value => value % 2 == 0, container));

python

def myFilter(predicate, container):
    sieve = []

    for element in container:
        if predicate(element):
            sieve.append(element)

    return sieve

container = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(myFilter(lambda value: value % 2 == 0, container))

Individual evidence

  1. Christian Ullenboom: Java is also an island . 13th updated edition. Galileo Press, Bonn 2017, ISBN 978-3-8362-5869-2 , 8.5 Anonymous inner classes ( openbook.galileocomputing.de ).
  2. Angelika Langer: Lambda expressions and method references. November 2013, accessed April 17, 2020 .