Functions
Like mathematical functions, Sidef's functions can be recursive, take arguments and return values.
func hello (name) {
say "Hello, #{name}!"
}
hello("Sidef")The special __FUNC__ keyword refers to the current function:
func factorial (n) {
if (n > 1) {
return (n * __FUNC__(n - 1))
}
return 1
}
say factorial(5) # prints: 120Closures
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.
func curry(f, *args1) {
func (*args2) {
f(args1..., args2...)
}
}
func add(a, b) {
a + b
}
var adder = curry(add, 1)
say adder(3) #=> 4Caching functions
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:
Last updated
Was this helpful?