import ballerina/io;

// Anonymous function syntax.
var isOdd = function(int n) returns boolean {
    return n % 2 != 0;
};

// Function type syntax.
type IntFilter function (int n) returns boolean;

// Module-level function definition.
function isEven(int n) returns boolean {
    return n % 2 == 0;
}

public function main() {
    // The `isEven` function  referred as a value.
    IntFilter f = isEven;

    int[] nums = [1, 2, 3];

    // Arrays provide the usual functional methods: 
    // `filter`, `map`, `forEach`, and `reduce`.
    int[] evenNums = nums.filter(f);

    io:println(evenNums);

    // Shorthand syntax when the type is inferred and the body is an expression.
    int[] oddNums = nums.filter(n => n % 2 != 0);

    io:println(oddNums);
}

Function values

Functions are values and work as closures. Function type is a separate basic type. Anonymous function and type syntax look like function definition without the name.

import ballerina/io;
var isOdd = function(int n) returns boolean {
    return n % 2 != 0;
};

Anonymous function syntax.

type IntFilter function (int n) returns boolean;

Function type syntax.

function isEven(int n) returns boolean {
    return n % 2 == 0;
}

Module-level function definition.

public function main() {
    IntFilter f = isEven;

The isEven function referred as a value.

    int[] nums = [1, 2, 3];
    int[] evenNums = nums.filter(f);

Arrays provide the usual functional methods: filter, map, forEach, and reduce.

    io:println(evenNums);
    int[] oddNums = nums.filter(n => n % 2 != 0);

Shorthand syntax when the type is inferred and the body is an expression.

    io:println(oddNums);
}
bal run function_values.bal
[2]
[1,3]