Functions
Like mathematical functions, Sidef's functions can be recursive, take arguments and return values.
The special __FUNC__
keyword refers to the current function:
Closures
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.
Caching 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 Perl 6 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