LEARN VOID / 04

Functions

Name an idea. Use it again.

Complete program for the synchronous entry adapter. The result below is the returned integer.

functions.voidDownload source
func subtotal(unit_price: i32 = 12, quantity: i32 = 1) -> i32:
    return unit_price * quantity

func entry(quantity: i32) -> i32:
    return subtotal(
        quantity = quantity,
    )
Input 5Expected result 60

Name a reusable calculation

subtotal takes an integer unit price and quantity, then returns their product. The entry function names quantity and leaves unit_price at its default of twelve: five items return 60. The multiline call permits a trailing comma. Required parameters must precede defaulted ones; supplied positional arguments must precede named arguments.

Give recursion a stopping point

A recursive function calls itself with a smaller problem. The separate function fragment below computes factorial for non-negative integers. Its base case is 0! = 1; input 5 gives 120. Add it to a source file and call factorial(5) from a function. It is not a standalone CLI program.

factorial.voidDownload fragment
func factorial(number: i32) -> i32:
    if number == 0:
        return 1
    else:
        return factorial(number - 1) * number

Keep the domain clear

Use small non-negative inputs for this factorial fragment. Values through 12! fit in i32; larger products wrap. Negative inputs do not reach this fragment’s base case.

Clear calls, predictable defaults

Functions and receiver methods accept named arguments in any order after a positional prefix. Supplied expressions evaluate once in written order. Defaults are pure compile-time expressions resolved in the declaration’s module; they cannot depend on parameters, the receiver or runtime function calls. A concrete literal default can infer a parameter type. Generic parameters still need annotations. Function values require all arguments positionally.