BlyxDocumentation
Browse chapters
Documentation / Language essentials

Functions, parameters and results

Give a calculation a name, call it more than once, and use its return value in another expression.

Define the interface

Read fn total(price: i64, quantity: i64) -> i64 as a function named total taking two signed integers and returning one signed integer. A parameter names a value inside the function. An argument is the value supplied by a call.

Trace a call

In total(7, 3), price receives 7 and quantity receives 3. The function multiplies them, finishes, and the caller receives 21. The binding first keeps that result in main. The second call uses new arguments and its result is added to first.

Return from a block

A final expression without a semicolon supplies the result. You can also write return price * quantity; to exit explicitly. A semicolon discards a final expression’s value. Keep an explicit return type on functions that return values when compiling a native executable.

Keep calculation separate from output

total can serve a receipt, a test or a larger calculation because it returns its answer. main decides what to print. Parameters belong to each call. Declare a local mutable accumulator when you need a value to change inside the function.

Try the program

Output Ready
Expected output
21
29
Open in the full playground →

Practice

Make the second order four units at four credits. Print the combined total for both orders.

Hint

Only the second call in main needs different arguments.

Worked solution

The first order is 21 and the second is 16. Their sum is 37.

Find

total(4, 2)

Replace with

total(4, 4)

Output after the change

21
37