Function literal syntax - ntrel/vdev GitHub Wiki
Consider this generic function declaration:
fn add(x!, y!) {return x + y}
Argument type inference is also useful when passing a function as a function argument. Below, add
's argument types can be inferred from the op
function parameter type it is passed to:
fn calculate(int a, int b, op fn(int, int)int)
{
return op(a, b);
}
...
x := calculate(2, 3, add) // passes add<int>
assert x == 5
For a more practical example, see the find
example at the end.
Function literal syntax is useful when a function will only be used in one place. Here, inference can also help:
fn (x, y) {return x + y} // function literal
For the above literal, argument type inference is implied - no need to write (x!, y!)
. Note that these literals are actually implemented as generic functions. Function literals can also specify the argument types so they are not generic. Then one can be assigned to a variable.
Lambda functions imply return
:
fn x! + y! // same as above function literal
The lambda argument list is deduced from the order of use of x! and y!. If the order must be different (which is unusual), then a function literal can be used instead.
Here's a practical example to find the portion of an array that starts with a certain value. We pass a function pred
that returns true if the value was found. It returns a slice of the array starting with the found value.
(For simplicity, I'm not using a generic function for find
):
fn (arr []int) find(pred fn(int)bool) []int {...}
...
a := [1,2,3]
b := a.find(fn e! == 2) // [2,3]
c := a.find(fn e! * e > 5) // [3]
Notice that for c
, the second time e
is used in the lambda expression, it does not use inference, as only the first use can have inference.