Skip to Content
ReferenceLanguage

10. Input, output and program shape

The normative CP Lang 0.3 specification.

This is the normative specification (source). For a gentler introduction, start with the guides.

Status: draft for 0.3.0. Sources: archived design/spec/25-io.md, 31-interaction.md, 32-graders-bundling.md; decisions 20, 136, 139. Nothing here is compiler-special except return-type dispatch: I/O is byte intrinsics, two traits, and the io context.

10.1 Program shape

A program is a flat sequence of top-level statements run top to bottom; there is no required main or solve.

let sv = Sieve(1e6)                   // runs once

@!multitest
let n: 1..=2e5 = read()               // runs once per test case
let a = read<[n]Int>()
print(a.sum())
  • @!multitest reads the test count and runs everything below it per case; @!multitest(until_eof) runs until input ends. State declared below the divider is per-test, and a fresh type declared below it can not leak into the next case (chapter 2). (R10.1.1)
  • Top-level return ends the program, or the current case under @!multitest. (R10.1.2)
  • IOI-style tasks mark entry points with @grader, @grader(interactive) or @grader(two_phase) on a fn or mod, and declare judge-provided functions with extern fn. The judge profile supplies the harness; local runs use a generated stub (decision 136). (R10.1.3)

10.2 Reading

trait Read: fn read() -> Self uses io
fn read<T: Read>() -> T
  • read<T>() dispatches on the expected type, so let n: 1..=2e5 = read() and read<[n]Int>() are the same mechanism. (R10.2.1)

  • Range types read with their contract. A domain written with explicit ends (1..=n, 0..n, lo..=hi) reads and prints its positions as their integers, never shifted. io.base applies only to counted domains, declared by a count alone ([n]T, or domain E = [m], where [m] in a domain declaration is shorthand for 0..m): with io(base: 1) makes 1-based input for them 0-based positions, and back on output. So the two never stack. Sizes, cuts and plain integers never convert. (R10.2.2)

  • Arrays [D]T read D.count values; [R, C]Char reads rows of characters with no separators; [V]List<V> reads count-prefixed rows; [Pair<V>]T reads a lower triangle without its diagonal (row i gives the values for every earlier j), since it walks in that order; records, tuples and structs read their fields in order; an enum reads one token, picks the variant whose tag (or name) it equals (an integer @tag(1) compares as a number, so 01 matches), then reads that variant's fields, so a command stream is read<Cmd>() in a loop; Range<T> reads two ends l r as the inclusive l..=r, the statements' convention, and checks l <= r; Bool is not a token type (read<Bool>() is E0315), and yes(b) prints io.answers, ("YES", "NO") in the default profile; Str reads one token; read_line() reads the rest of the line; Char skips whitespace then reads one character. Mod<P> reads one signed integer token of any length and reduces it modulo P, so a 10^4-digit coefficient is read<Mod<P>>(). (R10.2.3)

  • s.parse<T>() reads a T from a string by these same rules, None on a bad or leftover token: one token read under two moduli is let s = read<Str>() then s.parse<Mod<P>>()! and s.parse<Mod<Q>>()!. (R10.2.4)

  • Graphs are built from an edge list read as records, read<[E](u: V, v: V)>(), then Graph.undirected(edges) or .directed (lib/graphs-trees.md); there is no Graph.read. (R10.2.5)

  • A bad token traps with the input position and the expected type. (R10.2.6)

  • read_all<T>() reads every remaining T until the input ends, for statements that give no count; reading after it is an error. O(tokens). read_all<T>(until: f) stops at the first value with f true, a sentinel, which it consumes and leaves out; reading may continue after it (decision 161). (R10.2.7)

10.3 Printing

  • print(x, y, ...) joins by io.sep and ends the line; print(xs) prints a sequence on one line; print(xs, sep: "\n") overrides; print(xs, none: -1) prints each absent element of a ?T sequence as -1. (R10.3.1)
  • Interpolated strings format each piece through Print; positions print in the file's base; "{x:.9}" sets float precision. (R10.3.2)
  • Bool is not Print: print(b) is an error naming print(yes(b)). yes(b) is the word from io.answers, a Str, so it also works in interpolation (yes(b, answers: ("Possible", "Impossible"))). (R10.3.3)
  • F64 uses io.precision or print(x, precision: k). (R10.3.4)
  • Derived structurally (see R08.1.6), with nothing to write: records, tuples and structs print their fields joined by io.sep; enums print their variant name unless the type implements Print. (R10.3.5)
  • Output mirrors input, shape for shape, except that counts are never written for you. [R, C]Char prints one row per line with no separators. Any other [R, C]T, a [V]List<T> and a List<List<T>> print one inner row per line, joined by io.sep. [Pair<V>]T prints its lower triangle row by row. To print a count-prefixed row, print the count: print(xs.len, xs) prints the length and the elements on one line. (R10.3.6)

10.4 Interaction

Wire switches to interactive mode: every read and every exit flushes first. A query is wire.ask("? {x} {y}"): print a line, flush, and read the answer as the type the call site expects (fn ask(x: Int, y: Int) -> Int = wire.ask("? {x} {y}")). A program that never constructs one never flushes early. A trap in any mode flushes buffered output before writing to stderr. The local interactor harness (cpl interact, tools/stress.md) runs the program against an @interactor fn or an external binary.

10.5 Signatures

read and print are core, so they have no stub in spec/std. Their exact forms:

fn read<T: Read>(base: Int = io.base) -> T
fn read_line() -> Str
fn read_all<T>(until: ?(T -> Bool) = None) -> List<T>       // std.io
fn print(xs: Print..., sep: Str = io.sep, end: Str = "\n",
         none: ?Print = None, precision: ?Int = io.precision)
fn yes(ok: Bool, answers: ?(Str, Str) = None) -> Str                // std.io

print takes any number of positional values. A sequence argument prints its elements joined by sep. none: replaces each absent element of a ?T sequence. ?T is not Print, like Bool, so printing one without none: is a compile error that names it. end: "" leaves the line open.

10.6 Cost

Input is one bulk read and a hand-rolled parser; output is one buffer written at exit (or per flush in interactive mode). io is a compile-time context, so - io.base folds away.

On this page