-
Notifications
You must be signed in to change notification settings - Fork 24
Functions
Functions can be defined in many ways, they are used here to create similar functions:
fun add(a, b) {
return a + b;
}
// or
fun add(a, b) -> a + b;
var add = fun (a, b) {
return a + b;
};
// or
var add = (a, b) -> {
return a + b;
};
var add = fun (a, b) -> a + b;
// or
var add = (a, b) -> a + b;
Functions have access to all variables visible to their scope, even when called from different scopes (see closures).
Sometimes functions need to accept a variable length of arguments. This can be done by prefixing the last argument with ...
. When the function is called, that argument will be an array of the values after the normal arguments.
fun add(a, b, ...nums) {
var sum = a + b;
foreach (var n in nums) {
sum += n;
}
return sum;
}
printLn(add(1, 2, 3, 4, 5, 6));
Calling a function with a variable length of arguments can be done by prefixing the argument with ...
. Unlike packing, unpacking can be done on any (or all) arguments.
var setA = [1, 2, 3];
var setB = [4, 5, 6];
printLn(add(...setA, ...setB));
Mond supports basic tail call optimization on named functions.
fun loop(i) {
if (i == 0)
return 'done';
return loop(i - 1);
}
printLn(loop(10000));
Functions and sequences can be used as custom operators by changing their name to a valid operator and surrounding it in parenthesis:
fun (<>)(x, y) -> x != y;
printLn(1 <> 2);
These functions must be declared in the top-level scope and exist globally.
Names must not conflict with builtin operators and must consist of any combination of these characters: . = + - * / % & | ^ ~ < > ! ? @ # $ \
They must have one or two arguments and neither of them can be packed (...
).