Skip to Content
Guides

Language tour

A guided walkthrough of syntax, program layout, and everyday contest idioms.

You already know how to solve the problem. This chapter is about expressing the solution in CP Lang: indentation instead of braces, ?T instead of sentinels, structural [0..n]T arrays alongside nominal domains, and a file that reads like the flow of your algorithm.

Values, ranges, and mutation

Use let by default, var for bindings that change, and const for compile-time constants. Int is the default 64-bit signed integer. A range type states the problem's constraint right where the value enters the program.

let n: 1..=100 = read()
domain V = 1..=n
let a: [V]0..=1000 = read()
var total = 0
for v in V:
    total += a[v]
print(total)

Range-typed storage uses the smallest fitting integer width while arithmetic runs in 64-bit Int. ?Int represents every 64-bit Int plus none, and the compiler can pack optional layouts when proven safe rather than reserving Int.MIN. Use U64, I128, and F64 when you specifically need unsigned 64-bit, 128-bit, or floating-point arithmetic.

When you want a plain integer-indexed array without introducing a nominal domain, write the bounds directly and reset with .fill:

let n: 1..=100 = read()
let k: 1..=100 = read()
let a: [0..n]0..=k = read()

var cnt: [0..=k]Int = 0
for i in 0..n:
    cnt[a[i]] += 1
print(cnt)

In CP Lang, cnt.fill(0) resets the entire array in place (and seen.fill(none) resets a [D]?T table between test cases).

Missing is a value

?T means “a T, or none”. ?? supplies a fallback, if let binds a present value, and opt! unwraps when you know it exists. A missing answer is not -1, and an unreachable distance is not 1e18.

let n: 1..=100 = read()
domain V = 1..=n
let a: [V]Int = read()

var best: ?Int = none
for v in V:
    if a[v] % 2 == 0:
        best = max(best ?? a[v], a[v])
print(best ?? -1)

?Int and ?F64 lift arithmetic (+, -, *, /, %, **, unary -/+) and bitwise (&, |, ^, <<, >>, ~) operators by absorbing none, while min, max, min=, and max= skip it, so dist[v] min= dist[u] + w is a complete relaxation step with no INF. min(a, b) returns a definite T as soon as one side is a plain T. Compound +=, -=, ?V + k, and sum never lift over ?T; write dp[u] = dp[u] + w when you want absorbing addition. When none means failure rather than infinity, test it explicitly instead of relying on min= to skip it. Stepping a domain position by an integer (v + 1, v - 1, v + k) also returns ?V, so stepping off either end can never silently read out of bounds. Neither ?T nor Mod<P> implements Ord; when sorting records with optional fields, place none explicitly (by: x => (x.d == none, x.d ?? 0)).

Functions, nested helpers, and explicit mut

Parameters borrow read-only by default. A function that mutates an argument marks it mut, and the caller writes mut too. There is no implicit deep copy of an array.

domain V = 1..=3
var a: [V]Int = 0
fn add_to(mut a: [V]Int, v: V, delta: Int):
    a[v] += delta

add_to(mut a, V(1), 3)
let snapshot = a.copy()

A plain nested fn can read and mutate captured outer var bindings directly—ideal for a DFS that updates vis and order without threading extra parameters:

domain V = 1..=4
let g = Graph.undirected([(V(1), V(2)), (V(2), V(3)), (V(2), V(4))])
var vis: [V]Bool = false
fn dfs(u: V):
    vis[u] = true
    for v in g[u] if not vis[v]:
        dfs(v)
dfs(V(1))
print(vis.count(x => x))

Read ownership & borrowing for the lexical rules behind mut borrows and lends projections.

Parallel assignment, explicit undo, records, and choices

Swap or step coupled state with parallel tuple assignment—the right-hand side is evaluated completely before any binding is written:

let (a, b) = (48, 18)
var (r0, r1) = (a, b)
while r1 != 0:
    let q = r0 / r1
    (r0, r1) = (r1, r0 - q * r1)

There is no defer. Undo is one explicit line after the work it covers, which also works across sibling branches and early returns:

domain V = 1..=3
var dsu = Dsu<V>()
fn solve(v: V) -> Bool: dsu.unite(V(1), v)
let left = V(3)
let snap = dsu.mark()
solve(left)
dsu.undo_to(snap)

print(dsu.components)

var cur: List<Int> = []
fn dfs(step: Int):
    if step == 3:
        print(cur)
        return
    for x in 0..2:
        cur.push(x)
        dfs(step + 1)
        cur.pop()
dfs(0)

Name record fields instead of remembering .first.second, and match enums exhaustively with bare variant names:

let n: 1..=100 = read()
let m: 0..=100 = read()
domain V = 1..=n
var a: [V]Int = 0
type Edge = (u: V, v: V, w: 1..=1e9)
let edges: [0..m]Edge = read()

enum Move:
    Add(v: V, delta: Int)
    Ask(l: V, r: V)

let move = Add(V(1), 5)
match move:
    Add(v, delta) => a[v] += delta
    Ask(l, r) => print(sum(a[v] for v in l..=r))

A few C++ habits to leave behind

  • Write and, or, and not for logical operators, and elif, never else if. Multi-line expressions continue inside (...)/[...]/{...} or after a trailing binary operator (and, or, +, -, *, ...); breaking before an operator requires (...).
  • Mutate elements through an indexed loop (for i in 0..xs.len: xs[i].f()); there is no for mut x in xs.
  • .. excludes the end; ..= includes it. Open-ended ranges ..i, ..=i, and i.. work in slices and range structures (st.fold(..i)).
  • Stepping a nominal domain position with v + k or v - k returns ?V: handle it with if let, ??, or !. v.cyc(k) wraps cyclically.
  • Use x min= y and x max= y (any two-argument function works as x f= y).
  • Integer division / and remainder % use Euclidean semantics: remainder is always in 0..|b|, so -7 / 3 is -3 and -7 % 3 is 2. When operands are proven non-negative, C++ codegen lowers straight to native / and %. // is always a line comment.
  • Break out of nested loops with labels: 'outer: for r in Row: and break 'outer.

Program structure

A program is its top-level statements, run in order from top to bottom. There is no fn main() and no fn solve() wrapper, with one test case or with many:

let n: 0..=2e5 = read()
if n == 0:
    print("empty")
    return
domain V = 1..=n
let a: [V]Int = read()
print(a.sum())

A top-level return ends the program. It takes no value and works from inside any loop.

When the input holds many test cases, add one line. @!multitest is a divider. The ! marks a directive for the rest of the file, where a plain @ decorates only the one item below it: everything above it runs once, and everything below it runs once per test case. The number of test cases is read for you at the divider.

let sv = Sieve(1e6)             // above the divider: built once, shared by every test case

@!multitest
let n: 0..=2e5 = read()         // below the divider: once per test case
if n == 0:
    print("empty")
    return                      // ends this test case; the next one starts
domain V = 1..=n
let a: [V]Int = read()
print(a.sum())

The code below the divider is the single-test program, unchanged and unindented. Three things follow from the divider:

  • Each test case runs in a fresh scope. Its lets, vars, domains and functions are created anew and are gone when the case ends, so nothing leaks into the next one.
  • A @memo fn below the divider belongs to its test case: the cache starts empty every time.
  • Below the divider, return ends the current test case only. Above it, return still ends the program.

State that must outlive a test case (a sieve, precomputed factorials, a lookup table) is declared above the divider. @alt and @check read the top-level input lets by name in both shapes: the program's inputs in a single-test file, or the current test case's inputs below the divider.

@!multitest(until_eof) reads test cases until the input ends instead of reading a count. For any other shape, write a plain for _ in 0..tests: loop; a @memo fn nested in it resets on every iteration. Library modules contain only declarations—importing a helper never reads input or mutates hidden global state.

On this page