Skip to Content
Guides

Idioms

Gold-standard CP Lang idioms: domains, optionals, reductions, grids, and stdlib structures.

Gold-standard CP Lang solutions read like the editorial: the header states the invariant in two to five lines, each index space has one domain, each bound or modulus is written once, and standard structures are named rather than re-derived inline. Every snippet below is checked by cpl check and cpl build in the gate.

1. One fact in one place: bounds, domains, and moduli

Write every constraint and modulus once at the top of the solution (const, type Z = Mod<...>, domain), then let types carry bounds through every array and loop:

const LIM = 200_000
type Z = Mod<998_244_353>

let n = 5
domain V = 1..=n
let a: [V]Int = [1, 2, 3, 4, 5]
var total: Z = 0
for v in V:
    total += a[v]
print(total)

When a problem has two distinct index spaces (items vs cuts, rows vs columns, vertices vs edges), give each its own domain so swapping them is a compile-time error (E0301), not a silent WA:

domain Item = 1..=3
domain Cut = 0..=3
let weight: [Item]Int = [4, 7, 2]
var pref: [Cut]Int = 0
for i in Item:
    let k = i.ord
    pref[Cut(k + 1)] = pref[Cut(k)] + weight[i]
print(pref[Cut(3)])

2. Searches and reductions instead of flag loops

Prefer any, all, sum, count, min, and max over manual boolean flags and accumulator loops (enforced by lints L0501, L0504, L0505):

let xs: List<Int> = [3, 8, 2, 9, 5]
let has_big = xs.any(x => x > 7)
let all_pos = xs.all(x => x > 0)
let evens = xs.count(x => x % 2 == 0)
let total = sum(x for x in xs)
print(yes(has_big), yes(all_pos), evens, total)

Use for x in xs if cond: to filter cleanly without extra nesting, and xs.adjacent / zip / enumerate instead of for i in 0..xs.len::

let xs: List<Int> = [2, 5, 4, 9]
let asc = xs.adjacent.count(p => p.0 < p.1)
let pos_sum = sum(x for x in xs if x >= 4)
print(asc, pos_sum)

3. Zero-sentinel optionals (?T) and min= / max=

Never invent -1 or 1e18 sentinels, and never initialize var best = 0 before best min= x (since 0 would stay smaller than any positive value). Use ?Int with min= / max=, if let, ??, and early-return let x = opt ?? return:

fn best_even(xs: List<Int>) -> ?Int:
    var best: ?Int = none
    for x in xs if x % 2 == 0:
        best max= x
    best

print(best_even([1, 3, 5]) ?? -1)
print(best_even([1, 4, 9, 2]) ?? -1)

4. Grids without dx / dy boilerplate

Model grid coordinates as (Row, Col). Every cell automatically exposes in-bounds .adj4 and .adj8 neighbors with zero manual bounds checks:

let (h, w) = (2, 3)
domain Row = 0..h
domain Col = 0..w
var deg = 0
for r in Row:
    for c in Col:
        for (nr, nc) in (r, c).adj4:
            deg += 1
print(deg)

5. Sorting, heaps, bags, and frequency tables

Use key functions with desc(...) for multi-key sorting, MinHeap / MaxHeap for priority queues, SortedBag for multisets (remove_one), and HashMap where m[k] returns V directly (auto-inserting the default on miss — never apply ?? or ! to m[k]) while m.get(k) returns ?V:

var pts: List<(Int, Int)> = [(2, 5), (1, 3), (2, 1)]
pts.sort(by: p => (p.0, desc(p.1)))

var freq: HashMap<Int, Int> = HashMap()
for (x, _) in pts:
    freq[x] += 1

var h: MinHeap<Int> = MinHeap()
for x in [7, 2, 9]:
    h.push(x)
print(pts[0].0, pts[0].1, freq[2], h.pop() ?? -1)

6. Binary search and prefix sums

Use integer binary search on a monotone predicate with explicit lo/hi invariants, or lower_bound / upper_bound on sorted lists:

// First x in 1..=100 whose square is at least 50.
var lo = 1
var hi = 100
while lo < hi:
    let mid = lo + (hi - lo) / 2
    if mid * mid >= 50:
        hi = mid
    else:
        lo = mid + 1
print(lo)

7. Standard data structures: DSU, Fenwick, and Segment Trees

Import battle-tested data structures from std.* instead of re-deriving them inline:

use std.dsu.Dsu
use std.fenwick.Fenwick

domain V = 1..=4
var dsu = Dsu<V>()
let _ = dsu.unite(V(1), V(2))
let _ = dsu.unite(V(2), V(3))

var bit = Fenwick<V>()
bit.add(V(1), 5)
bit.add(V(3), 7)
print(yes(dsu.same(V(1), V(3))), yes(dsu.same(V(1), V(4))), bit.prefix(V(3).r))

8. Quick idiom reference

Every block below is a complete program checked by the compiler when this site is built.

Read n and a 1-based array

Name the index space once; the array, its loops and its queries all use it.

let n: 1..=2e5 = read()
domain V = 1..=n
let a: [V]Int = read()
print(a[V(1)], a.sum())

[0..n] or [0..=n]

[0..n]T has n cells; [0..=n]T has n + 1, so use it when n itself is a DP state. sorted() returns a 0-indexed list.

let n = 4
var count: [0..n]Int = 0
var dp: [0..=n]Int = 0
dp[n] = 1
let sorted = [3, 1, 2].sorted()
print(count.len, dp.len, sorted[0])

Strings and characters

A Str is ASCII: s[i] is a Char, and c - 'a' is an Int. Compare characters with two comparisons. A slice is a view; .to_str() copies it when it must outlive the string or be appended.

let s: Str = read()
let c = s[0]
fn head(s: Str, k: Int) -> Str: s[..k].to_str()
var out = ""
out += s[2..4].to_str()
print(s.len, yes('a' <= c and c <= 'z'), c - 'a', head(s, 3), out)

Printing

print separates arguments with a space and ends the line; end: and sep: change that. A [D]Char prints as one word. Interpolate with "{n}".

let chars: [3]Char = read()
let n = 4096
print(chars)
print(chars, sep: " ")
for x in [1, 2, 3]:
    print(x, end: " ")
print()
print("{n}".len, n.digits())

YES and NO

print does not take a Bool. yes(ok) gives YES or NO; with io(answers: ...) changes the words for a scope, and answers: for one call.

let ok = 3 > 2
print(yes(ok))
with io(answers: ("Yes", "No")):
    print(yes(ok))
print(yes(ok, answers: ("Possible", "Impossible")))

Maps

m[k] += 1 starts an absent key from zero. Reading an absent m[k] traps (R0001), so read with m.get(k), which is optional. ??= fills an absent entry and hands it back.

var cnt: Map<Int, Int> = Map()
cnt[7] += 1
cnt[7] += 1
var groups: Map<Int, Set<Int>> = Map()
(groups[1] ??= Set()).add(5)
print(cnt[7], cnt.get(8) ?? 0, groups[1].len)

Grids

One pair of brackets, comma-separated indices.

var g: [2, 3]Int = 0
g[1, 2] = 5
print(g[1, 2])

Modular arithmetic

The modulus is part of the type. ** is power and .inv is the inverse.

type Z = Mod<998244353>
let z = Z(3)
print(z, z ** 2, z.inv * z)

Swap, reverse, adjacent pairs

Swap with a tuple assignment. reverse() works in place; .rev iterates backwards.

var (a, b) = (1, 2)
(a, b) = (b, a)
var xs = [1, 4, 9]
(xs[0], xs[2]) = (xs[2], xs[0])
xs.reverse()
for (p, q) in xs.adjacent:
    print(q - p, end: " ")
for i in (0..3).rev:
    print(i, end: " ")
print(a, b)

Clearing between tests

fill resets an array in place.

var a: [0..4]Int = 7
var seen: [0..4]?Int = None
seen[1] = 3
a.fill(0)
seen.fill(None)
print(a, seen[1] ?? -1)

mut parameters

A function that changes its argument says mut, and so does the caller. To change a value locally, copy it into a var.

fn bump(mut x: Int): x += 1
fn twice(x: Int) -> Int:
    var cur = x
    cur *= 2
    cur
var v = 1
bump(mut v)
print(v, twice(v))

Long expressions and match

Break a line inside parentheses. A match arm is pattern => expression.

let total = (1 + 2
    + 3)
let kind = 2
let name = match kind:
    1 => "one"
    _ => "many"
print(total, name, abs(-3), min(2, 5), max(2, 5), gcd(12, 18), lcm(4, 6))

Multiple test cases

@!multitest reads the count and runs the rest of the file once per test. return ends the current test.

@!multitest
let n: 1..=100 = read()
if n == 1:
    print(0)
    return
print(n * 2)

Stress test against a brute force

Mark the slow version @alt(main) in the same file and run cpl stress. Inputs are generated from the types at read.

let n: 1..=8 = read()
let a: [n]1..=20 = read()
print(a.max()!)

@alt(main)
fn slow():
    var best = 0
    for x in a: best max= x
    print(best)

On this page