Skip to Content
Read

Functions, records and match

fn, mut parameters, records, enum and match.

A contest solution is mostly one flow from input to output, and functions are where you name a step. This chapter covers the four pieces that carry most of that: functions, mut parameters, records and enum with match.

Functions

A function has typed parameters and a return type. A one-line body goes after =; a longer one is an indented block whose last line is the result.

Output
Press Run (Ctrl+Enter).

Functions can be declared anywhere in the file and can call themselves. A function written inside another one sees the outer function's variables, which is how a DFS reads the graph without passing it along:

Output
Press Run (Ctrl+Enter).

if ... else is an expression: its value is the branch taken.

Changing an argument: mut

Arguments are values. A function that changes one says so in its signature, and so does the caller, so you can see at the call which data may change:

Output
Press Run (Ctrl+Enter).

Without mut at the call, this does not compile.

Records

A record type groups named fields. It reads from input field by field, so the input format is the type:

Output
Press Run (Ctrl+Enter).

Tuples compare field by field, so (score, -time) is "higher score, then less time". The loop keeps the index of the best player, not a copy: a record taken from ps in a loop is lent from ps, and storing it in an outer var does not compile (ps[i].copy() would make one).

Enums and match

When a value is one of a few kinds, each with its own data, write an enum. match takes it apart, and the compiler checks that every kind is handled:

Output
Press Run (Ctrl+Enter).

match also works on numbers and characters, with _ for "anything else". That is the usual way to act on an operation read from input.

Problem: Plus or times

A number x starts at 1. Apply q operations + y or * y (0 ≤ y ≤ 10⁹) in order, and print x modulo 10⁹ + 7. For + 4, * 3, + 1 the answer is 16.

4 tests · Ctrl+Enter
Hints

apply(x, op, y) is one match on the character; the remainder is taken after every step.

Next: Strings and output.

Lints for these patterns

cpl lint, the editor and the playground flag the hand-written versions of what this chapter teaches:

On this page