Skip to content

Anonymous functions

An anonymous function is a function you write with fn and store in a callable variable: callable $double = fn(int $x): int => $x * 2;. Usually it has no name. It has a name only when it calls itself.

fn

An anonymous function is a small function you write where you need it. You can keep it in a variable, pass it to another call or store it in a list.

fn is the only way to write one. After the arrow comes one expression, whose value the function returns, or a block in braces. Every parameter has a type. A block declares its return type. The function copies each outside variable it uses when the function is written.

$fn->bindTo($obj) and $fn->bind($obj) return a copy that uses $obj as $this. $fn->call($obj, ...) makes that copy and calls it. The object must be of the class the function was written in, or a subclass. Any other object, or null, throws a LogicError.

Good to know: there is no use (...) list. A call through a callable returns mixed.

The examples below write functions, show captures and check a form. Example 04 reads $this, 05 calls itself, and 06 does not compile.

Writing a small function where you need it

<?nvs
// Shows the two ways to write an anonymous function. After the arrow comes
// either one expression, whose value the function returns, or a block in braces
// that runs several lines and returns.
// One expression. The result is the value of `$x + 1`.
callable $next = fn(int $x): int => $x + 1;
// A block, for work that takes more than one line. A block says what it
// returns; only the one-expression form may leave the type out.
callable $total = fn(array<int> $amounts): int => {
int $sum = 0;
foreach ($amounts as int $amount) {
$sum = $sum + $amount;
}
return $sum;
};
// An anonymous function is called through its variable. The call returns `mixed`,
// so write `as` to say which type you are reading. This prints 8 12.
array<int> $prices = [3, 4, 5];
echo $next(7) as int, ' ', $total($prices) as int, "\n";
// An anonymous function is a value, so you can pass it directly to a call.
// This prints: BAG,BOX
array<string> $names = ['bag', 'box'];
array<mixed> $shouted = Core\Arr::map($names, fn(string $name) => Core\Str::upper($name));
echo Core\Str::join($shouted as array<string>, ','), "\n";
Output
8 12
BAG,BOX

What an anonymous function captures

<?nvs
// Shows what an anonymous function captures. It copies every outside variable it
// uses when the function is written. Changing that variable afterwards does not
// change what the function reads.
string $greeting = 'Hello';
callable $greet = fn(string $name): string => $greeting . ', ' . $name;
// The variable changes. The copy inside the function stays the same.
// This prints: Hello, Ada
$greeting = 'Goodbye';
echo $greet('Ada') as string, "\n";
// One anonymous function per round, each with that round's number. This prints 0,1,2
array<callable> $labels = [];
int $round = 0;
while ($round < 3) {
$labels = Core\Arr::append($labels, fn(): string => $round as string);
$round = $round + 1;
}
// `$label()` returns `mixed`, and `as string` converts it to a `tainted string`.
// So the array has the type `array<tainted string>`.
array<tainted string> $printed = [];
foreach ($labels as callable $label) {
$printed = Core\Arr::append($printed, $label() as string);
}
echo Core\Str::join($printed, ','), "\n";
class Discount
{
public function constructor(private int $percent)
{}
// Inside a method the object is captured too, so the function reads the
// property through it. This returns a callable the caller can keep.
public function rule(): callable
{
return fn(int $price): int => $price - Core\Math::quotient($price * $this->percent, 100);
}
}
// The callable still has the discount, wherever it is used.
// This prints 900 450
Discount $tenth = new Discount(10);
callable $apply = $tenth->rule();
echo $apply(1000) as int, ' ', $apply(500) as int, "\n";
Output
Hello, Ada
0,1,2
900 450

Checking a form with one rule per field

<?nvs
// Shows a common use of anonymous functions. One rule per field is kept in an
// array. Each rule is an anonymous function that returns the message for a bad
// value. The same loop then checks any form, so adding a field is adding a line.
class Form
{
// Each rule gets the value of its field. It returns an empty string when
// the value is fine.
public static function check(array<string> $values, array<callable> $rules): array<tainted string>
{
array<tainted string> $problems = [];
foreach ($rules as string $field => callable $rule) {
tainted string $message = $rule($values[$field] ?? '') as string;
if ($message != '') {
$problems = Core\Arr::append($problems, $field . ': ' . $message);
}
}
return $problems;
}
}
// The shortest length is written once and carried into the rule that uses it.
int $shortest = 8;
array<callable> $rules = [
'name' => fn(string $value): string => $value == '' ? 'please give a name' : '',
'email' => fn(string $value): string => Core\Str::contains($value, '@') ? '' : 'needs an @',
'password' => fn(string $value): string =>
Core\Str::length($value) < $shortest ? 'needs ' . $shortest . ' characters' : '',
];
array<string> $filled = [
'name' => 'Ada',
'email' => 'ada@example.com',
'password' => 'correct horse',
];
// Nothing is wrong with this one, so the list of problems is empty.
// This prints: filled in: 0 problem(s)
echo 'filled in: ', Core\Arr::count(Form::check($filled, $rules)), " problem(s)\n";
array<string> $empty = [
'name' => '',
'email' => 'ada.example.com',
'password' => 'short',
];
// This prints one line per field that failed its rule.
foreach (Form::check($empty, $rules) as tainted string $problem) {
echo $problem, "\n";
}
Output
filled in: 0 problem(s)
name: please give a name
email: needs an @
password: needs 8 characters

A function that reads this

<?nvs
// Shows an anonymous function that reads `$this`, one that captures a variable,
// and one with a block body.
class Counter
{
public int $base = 10;
// Inside a method, the function can read `$this`.
public function adder(): callable
{
return fn(int $x): int => $this->base + $x;
}
}
// The function copies `$prefix` when it is written, so it still uses "one".
string $prefix = 'one';
callable $tag = fn(string $s): string => $prefix . ':' . $s;
$prefix = 'two';
callable $sum = fn(array<int> $xs): int => {
int $t = 0;
foreach ($xs as int $x) {
$t += $x;
}
return $t;
};
// This prints one:x 6 15.
array<int> $ns = [1, 2, 3];
Counter $c = new Counter();
echo $tag('x'), ' ', $sum($ns), ' ', $c->adder()(5), "\n";
Output
one:x 6 15

A function that calls itself

<?nvs
// Shows an anonymous function that calls itself. Its name comes after `fn`,
// and the name works only inside the function.
callable $factorial = fn fact(int $n): int => $n <= 1 ? 1 : $n * fact($n - 1);
// The name also works with a block body.
callable $fib = fn fib(int $n): int => {
if ($n <= 1) {
return $n;
}
return fib($n - 1) + fib($n - 2);
};
// This prints 120 55.
echo $factorial(5), ' ', $fib(10), "\n";
Output
120 55

The function keyword

<?nvs
// Shows that `function` does not make an anonymous function. Write `fn` instead.
// proof: compile-error
callable $f = function (int $x): int { return $x + 1; };
Output
error[E0222]: anonymous `function` expressions are not supported
--> 06-the-function-keyword.nvs:5:15
|
5 | callable $f = function (int $x): int { return $x + 1; };
| ^^^^^^^^ write an anonymous function with `fn`
= help: use `fn(...) => ...` (an expression body) or `fn(...) => { ... }` (a block body)
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

These forms do not compile:

  • function (int $x) { … } is the error E0222.
  • fn(int $x) use ($k) => … is the error E0223.
  • static fn(…) => … is the error E0210.
  • An inout parameter is the error E0493, and int &$x is the error E0237.
  • A parameter without a type is the error E0808.
  • A block body without a return type is the error E0450.

With an expression body, the return type may be left out. The function then returns the type of the expression. A value of the wrong type is the error E0401 in an expression body, and the error E0403 after return in a block.

A captured variable is a copy. The function may change its copy, and the outside variable keeps its value. Each call starts again from the value that was captured: a function that adds 1 to its copy of $k = 1 returns 2 on every call. An object is not copied. A function that captured $b reads a property of $b that changed after the function was written.

A function cannot use the variable it is stored in. In callable $f = fn(…) => … $f(…) …, the inner $f is the error E0301, because $f has no value yet. Give the function a name instead: fn fact(int $n): int => … can call fact(…). The call is checked against the function's parameters and return type. Outside the function, fact is the error E0320.

$this outside a method, or inside a static method, is the error E0779.

A method reference names a method without calling it. Core\Str::length, self::f and static::f each give a callable. On an object, write (...) in place of the arguments: $p->add(...). A method that does not exist is the error E0405.

bindTo, bind and call can throw a LogicError for the wrong object. Its message starts `this callable uses $this, so it can only be bound to an object of class A . A function that does not use $this is returned unchanged, so any object works. A second argument is the error E0402`.

An anonymous function can be called where it is written: (fn(int $x): int => $x * 10)(4) gives 40.

How to call a callable is on the page Calling a function.

  • Do keep an anonymous function short. Write a method when it needs many lines.
  • Do write a method when other code also needs to call the function.
  • Do write the return type on an anonymous function with a block body.
  • Don’t change an outside variable after you create an anonymous function and expect it to use the new value. The function has a copy.
  • Don’t write function () {}. It does not compile. Use fn.