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())@!multitestreads 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
returnends 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 afnormod, and declare judge-provided functions withextern 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, solet n: 1..=2e5 = read()andread<[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.baseapplies only to counted domains, declared by a count alone ([n]T, ordomain E = [m], where[m]in a domain declaration is shorthand for0..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]TreadD.countvalues;[R, C]Charreads rows of characters with no separators;[V]List<V>reads count-prefixed rows;[Pair<V>]Treads a lower triangle without its diagonal (rowigives the values for every earlierj), 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, so01matches), then reads that variant's fields, so a command stream isread<Cmd>()in a loop;Range<T>reads two endsl ras the inclusivel..=r, the statements' convention, and checksl <= r;Boolis not a token type (read<Bool>()is E0315), andyes(b)printsio.answers,("YES", "NO")in the default profile;Strreads one token;read_line()reads the rest of the line;Charskips whitespace then reads one character.Mod<P>reads one signed integer token of any length and reduces it moduloP, so a 10^4-digit coefficient isread<Mod<P>>(). (R10.2.3) -
s.parse<T>()reads aTfrom a string by these same rules,Noneon a bad or leftover token: one token read under two moduli islet s = read<Str>()thens.parse<Mod<P>>()!ands.parse<Mod<Q>>()!. (R10.2.4) -
Graphs are built from an edge list read as records,
read<[E](u: V, v: V)>(), thenGraph.undirected(edges)or.directed(lib/graphs-trees.md); there is noGraph.read. (R10.2.5) -
A bad token traps with the input position and the expected type. (R10.2.6)
-
read_all<T>()reads every remainingTuntil 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 withftrue, 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 byio.sepand 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?Tsequence 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) Boolis notPrint:print(b)is an error namingprint(yes(b)).yes(b)is the word fromio.answers, aStr, so it also works in interpolation (yes(b, answers: ("Possible", "Impossible"))). (R10.3.3)F64usesio.precisionorprint(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 implementsPrint. (R10.3.5) - Output mirrors input, shape for shape, except that counts are never
written for you.
[R, C]Charprints one row per line with no separators. Any other[R, C]T, a[V]List<T>and aList<List<T>>print one inner row per line, joined byio.sep.[Pair<V>]Tprints 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.ioprint 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.