Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Function Results

Of course, functions can also return a value. To do so, you need to define the return type (using ->) as shown in the following example:

test

fn square(x: Scalar) -> Scalar {
    x * x
}

std::debug::assert_eq([square(8.0), 64.0]);

You may also use if to decide between different results.

test

fn pow(x: Scalar, n: Integer) -> Scalar {
    if n > 1 {
        x * pow(x, n - 1)
    } else if n < 1 {
        1.0 / x / pow(x, -n)
    } else {
        1.0
    }
}

std::debug::assert_eq([pow(8.0, 2), 64.0]);
std::debug::assert_eq([pow(8.0, -2), 0.015625]);

Of course returning a value twice is not allowed.

test

fn pow(x: Scalar, n: Integer) -> Scalar {
    if n > 1 {
        x * pow(x, n - 1)
    } else if n < 1 {
        1.0 / x / pow(x, -n)
    }
    1.0 // error: without else this line would return a second value
}

std::debug::assert_eq([pow(8.0, 2), 64.0]);
std::debug::assert_eq([pow(8.0, -2), 0.015625]);

Early Return

It is also possible to implement an early return pattern with the return statement.

test

fn pow(x: Scalar, n: Integer) -> Scalar {
    if n > 1 {
        return x * pow(x, n - 1);
    }
    if n < 1 {
        return 1.0 / x / pow(x, -n);
    }
    1.0
}

std::debug::assert_eq([pow(8.0, 2), 64.0]);
std::debug::assert_eq([pow(8.0, -2), 0.015625]);