Velo by Example: Higher-Order Functions

Functions in Velo can accept other functions as parameters, enabling a functional programming style.

A function that takes another function as a parameter. The parameter type func[int] means "a function returning int".

func apply(int x, func[int] f) int {
    f(x);
};

any square = func(int x) int {
    x * x;
};

int result = apply(5, square);  # 25

The built-in map method on arrays is a higher-order function. It takes a callback with (index, value) parameters.

array[int] nums = new array[int]{1, 2, 3, 4, 5};

array[int] doubled = nums.map(
    func(int i, int v) int {
        v * 2
    }
);  # [2, 4, 6, 8, 10]