Anonymous & higher order functions
As well as regular functions, V supports anonymous and higher-order functions.
Anonymous functions can be declared inside other functions:
Such functions do not have a name and can be passed to other functions as arguments:
In the example above, the run()
function takes another function as its second argument;
its type describes the function type.
Such a type is described as fn (<param_types>) <return_type>
, for example:
If the function returns nothing, then the return type is omitted.
In the example:
The variable double_fn
is of type fn (int) int
.
Function types are first class types, which means they can be used
as types on a par with, for example, int
or string
.
For example, you can have an array of functions:
Or a function map:
Anonymous functions can be called right after they are declared:
Thanks to type aliases, you can give names to function types:
V has duck-typing, so functions do not need to declare compatibility with a function type — they just have to be compatible:
Such a function can now be used wherever a Filter
is expected:
Compatible functions can also be explicitly cast to a function type:
The cast here is purely informational – duck-typing means that the resulting type is the same without an explicit cast: