In Sidef, all functions are first-class objects which can be passed around like any other object. Additionally, all functions (including methods) are lexical closures.
By specifying the cached trait in a function (or method) declaration, Sidef will automatically cache it for you.
Optional arguments
The parameters of a function can also be declared with a default value, which provides support for optional arguments.
The default value of a parameter is evaluated only when an argument is not provided for that particular parameter, and it can be any arbitrary expression:
Named parameters
This is a very nice feature borrowed from Raku which allows a function to be called with named parameters, giving us the flexibility to put the arguments in no specific order:
Variadic functions
A slurpy variable in the form of *name can be used as a function parameter to collect the remaining arguments inside an array:
Alternatively, by using a named variable in the form of :name, the arguments are collected inside an hash:
Typed parameters
A function can be declared with typed parameters, which are checked at run-time.
Now, the function can only be called with strings as arguments:
The typed parameters require a specific type of object, but they do not default to anything when no value is provided. This means that all typed-parameters are mandatory, unless a default value is provided:
func f(:pairs) {
say pairs #=> Hash(a=>1, b=>2)
}
f(a => 1, b => 2)
func concat(String a, String b) {
a + b
}
say concat("o", "k") # ok
say concat(1, 2) # runtime error
func concat(String a="foo", String b="bar") {
a + b
}
say concat() # prints: "foobar"
say concat("mini") # prints: "minibar"
say concat(1, 2) # this is still a run-time error