Here we have a simple function that returns the argument plus two.
import stdlib.*;
func add2(x int) int {
return x + 2;
}
exported func main() {
println("Half-Life " + add2(1));
}
Half-Life 3
Functions can optionally end in an expression, which will return the value for us.
func add2(x int) int { x + 2 }
We can also make a closure, a function inside another one.
import stdlib.*;
exported func main() {
add2 = (x int) => { x + 2 };
println("Half-Life " + add2(1));
}
We can leave the type off of a lambda's parameter, to make it shorter. 0
import stdlib.*;
exported func main() {
add2 = (x) => { x + 2 };
println("Half-Life " + add2(1));
}
In Vale, functions and methods are the same thing, so these two calls are exactly equivalent.
import stdlib.*;
import stdlib.stringutils.*;
import stdlib.collections.*;
exported func main() {
s1 = "Hail Hydra!".split(" ");
s2 = split("Hail Hydra!", " ");
}
This is known as Universal Function Call Syntax, or UFCS. This makes method chaining nicer, for example:
a.f(3).g(true).h("Yendor")
as opposed to
h(g(f(a, 3), true), "Yendor").
Taking out the parameter's type makes this a "generic" lambda, see generics for more.
Next: Modules