Skip to content

Functions

Dennis Rönn edited this page Oct 4, 2022 · 2 revisions

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.

Syntax

The syntax for a function follow this template

func <name>([$<type>: <name>[, ...]]) -> $<void|type> {
    <code>
}

Return

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.

Void

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.

Non-Void

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>;.

Examples

Here's 2 examples implementing Fibonacci and Factorial.

Fibonacci

func fib($number: n) -> $number {
    if (n <= 1) {
        return n;
    }

    return fib(n - 2) + fib(n - 1);
}

Factorial

func fac($number: n) -> $number {
    if (n <= 1) {
        return 1;
    }

    return fac(n - 1) * n;
}

Other Examples

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.

Clone this wiki locally