-
Notifications
You must be signed in to change notification settings - Fork 0
Functions
Functions in Dern are declared by the func keyword, can have any number of parameters, and may return 0 or 1 values.
Currently, parameters and return values are strict, meaning the type has to be defined.
The syntax for a function follow this template
func <name>([$<type>: <name>[, ...]]) -> $<void|type> {
<code>
}
There are two ways to return out of functions, depending on the return type. With void you don't return a value, otherwise you're required to return a value.
When returning void, meaning no return type, the syntax to return is by simply doing return;.
Reaching the end of a function normally also returns out of the function without having to do extra work.
When a function has a return type, you're required to return a value.
Same as void this is done using return, except this time the syntax is return <expression>;.
Here's 2 examples implementing Fibonacci and Factorial.
func fib($number: n) -> $number {
if (n <= 1) {
return n;
}
return fib(n - 2) + fib(n - 1);
}
func fac($number: n) -> $number {
if (n <= 1) {
return 1;
}
return fac(n - 1) * n;
}
As of writing there's no direct for loop in place, although you can still use recursion to get a similar effect, something languages like Haskell is known for with their immutable types and functional programming paradigm. Check this example for a simple loop printing the number 0 - 9:
func printNumLoop($number: n) -> $void {
if (n < 0) {
return;
}
printNumLoop(n - 1);
print(n);
}
printNumLoop(9);
Currently there's no support for lambdas, but when this is implemented, this may be a way I'll officially support loops.