Fuzion Logo
fuzion-lang.dev — The Fuzion Language Portal
JavaScript seems to be disabled. Functionality is limited.

Lambdas

Lambda expressions in Fuzion are syntactic sugar to produce values of function types.

Depending on the number of arguments, lambdas will create anonymous features that inherit from the Fuzion standard library features Function (general functions), Unary (functions with one argument, they can be composed), or Lazy (functions with no argument). Unary and lazy functions can be assigned to variables of type Function as well, if so desired.

Examples of Lambdas

A lambda expression is of the form a,b -> f a b or (a,b) -> f a b where a and b are the arguments of the lambda expression and f a b is an arbitrary expressions using these arguments to calculate a results. The following example uses a lambda expression x -> "Hello $x!" to map a sequence of names to strings that greet these persons. Then, a second lambda x -> say x is called for_each of these greetings to be printed:

In the next example, we use two lambda expressions to determine the average age from a sequence of persons given as tuples of their names and ages. First p -> p.1 is used to select the second part of the tuple, the age and calculate the sum of all ages. Next, p -> 1 is used to count the number of persons by summing up a 1 for each person:

Placeholder _

In the previous example, the lambda p -> 1 introduced a parameter p that was not needed in the subsequent expression. Whenever this is the case, an underscore _ can be used as a placeholder for an ignored parameter: _ -> 1:

Empty argument list

Lambdas might be nullary functions, i.e., there might be no arguments at all. In this case, the empty argument list must be enclosed by parentheses () as in the following code. Here, a feature repeat performs an action repeatedly until that action returns false.

The Fuzion syntax permits the expression following -> to be a block extending several lines at a higher indentation level. This is used in this example to count the number of calls in a mutable variable, print that count and to return false as soon as 10 iterations have been reached.

.
last changed: 2024-06-28