LEARN VOID / 04

Functions

Name an idea. Use it again.

Parameters, return values and a focused factorial example.

functions.voidDownload source ↓
# Factorial is defined here for non-negative inputs.
func factorial(number: i32) -> i32:
    if number <= 1:
        return 1
    return number * factorial(number - 1)

func entry(number: i32) -> i32:
    return factorial(number)
Input 5Expected result 120

Give the operation a name

factorial takes a number and returns its factorial: the product of the positive integers up to that number. The parameter and result both use i32.

Make recursion stop

The base case returns 1 for zero or one. For a larger input, the function multiplies the number by the factorial of the previous number. With input 5, that is 5 × 4 × 3 × 2 × 1 = 120.

Keep the example’s domain clear

The small entry function passes the input straight to factorial. Use non-negative inputs for this example. Results through 12! fit in i32; larger results wrap with integer arithmetic rather than becoming arbitrary-precision integers.