Lambda functions

A lambda is a function that you define without giving it a name. You create a lambda by surrounding your calculations with { and }.

{
    value = 42
    value += 2
}




The example above creates a lambda function, but just like a named function, it doesn't do anything unless you call it. In the next example, the lambda is assigned to a variable and called like any other function.

make value = {
    value = 42
    value += 2
}

make value()
<lambda>()
42
44


As you can see from the results above, the statements inside the lambda are run. Since the lambda doesn't return any value, the call to make value() has no result. Just like a function, if you want it to produce a value you need to return one. This example simply returns 2.

create two = { 2 }
create two()
<lambda>()
2

It isn't necessary to assign a lambda to a variable before calling it. You can create and call a lambda in one statement. This next example simply returns 2, just like the previous example:

{ 2 }()
2

Arguments

A lambda can accept arguments just like a named function, but they are declared differently. Inside the braces you list the names of the arguments followed by the word in, and then your calculations. This next example defines two arguments, first and second.

adder = { |first, second|
    first + second
}
adder(2, 3)
<lambda>(_ _)
5

5

Labels

Lambdas can't declare argument labels like a named function, but you can provide one to make it easier to read. In this example, the second argument is given a custom label:

add = { |first, second|  first + second }
add(2, to: 3)
<lambda>(_ _)
5

Implicit Arguments

Rather than explicitly declaring the names of a lambda's arguments, you can also use implicit arguments. An implicit argument is a # followed by a number. The number indicates which argument is being referred to (#1 for the first argument, #2 for the second, and so on). Implicit arguments work just like named arguments, but for short calculations they can be easier to understand.

add = { #1 + #2 }
add(5, to: 7)
<lambda>(_ _)
12

Lambdas as Values

Since lambdas are functions, they can act as values just like functions. You can assign them to variables, compare them to each other, pass them as arguments to other functions, and so on.

The examples above show lambdas assigned to variables, effectively giving them a temporary name. Another use of lambdas as values is passing them as an argument to another function. For example, the map function takes as arguments a sequence of values and a function used to transform them into new values.

map([1, 7, 11], { #1 + 2 })
map(2..4, { #1^2 })
[3, 9, 13]
[4, 9, 16]

map works by passing each element of the sequence through the given function and returning a list of the results. So in the first example, it will run 1 + 2, 7 + 2, and 11 + 2, putting those three results into a list and returning it.

Didn't find what you were looking for?

Contact Us