Skip to content

3. Literals

Taught in Scalars & Strings.

An integer literal is decimal, or hexadecimal, binary or octal after a 0x, 0b or 0o prefix (either case). A _ may stand between two digits. Its type is Int, except where a Byte is expected (below). It may have any number of digits, since an Int has no largest value (§4).

fn main()
    dbg 1_000_000 // 1000000
    dbg 0xFF      // 255
    dbg 0b1010    // 10
    dbg 0o77      // 63
end

1__0 and 10_ are errors (invalid integer "1__0").

Taught in Scalars & Strings.

An integer literal written where a Byte is expected is a Byte. A Byte is expected in:

  • an annotated binding or once, a Byte parameter’s argument or default, a Byte field of a struct literal, and a function’s result;
  • an element, key or value of a collection or tuple literal whose type is expected, and the payload of a generic constructor whose result is expected (Some(0x81) as a Maybe<Byte>);
  • each branch of an if or case whose value is expected, and an arm pattern over a Byte (0x80 -> ..., Some(0x80) -> ...).

With no expected type, a literal element or branch after a Byte one is a Byte too ([b, 0x42], if keep then b else 0x00). In a comparison and in &&&, ||| and ^^^, a literal operand takes Byte from the other operand (b == 0x80, bytes == [0x81, 0x00], b &&& 0x7F). A generic call is checked left to right, so in Iter.map(bytes, fn b -> b &&& 0x7F) the literal follows the Byte that bytes gives b.

fn tag(b: Byte) -> String
    case b
        0x00 -> "nul"
        0x7F -> "del"
        _    -> "other"
    end
end

fn main()
    bytes: List<Byte> = [0x81, 0x00, 0b0111_1111]
    dbg tag(0x7F) // "del"
    dbg bytes     // [129, 0, 127]
end

Only the literal itself, or the literal under a unary minus, takes its type from its position. n = 0x81 is an Int, and an Int value never becomes a Byte: b: Byte = n is type mismatch: expected Byte, got Int. Int.to_byte converts one.

A Byte literal outside 0 to 255 is an error in any spelling: `300` does not fit in a Byte (0 to 255), and the same for 0x100 and -1. -0 is a Byte literal has no sign: write `0` for `-0`.

Taught in Scalars & Strings.

A float literal is digits, a . and digits, with an optional exponent (e or E, an optional sign, digits). Digits with an exponent and no . are a float too. A _ may stand between two digits. Its type is Float.

fn main()
    dbg 3.14          // 3.14
    dbg 2.5e-3        // 0.0025
    dbg 1e10          // 10000000000.0
    dbg 1_000.123_456 // 1000.123456
end

Both sides of the . need a digit: .5 and 1. are not float literals.

Taught in Scalars & Strings.

A decimal literal is an integer or a float without an exponent, followed by d or D. Its type is Decimal (§4), and its text sets its scale: 1.50d has scale 2, 1.5d scale 1, 5d scale 0. A _ may stand between two digits, as in other number literals (1_000.00d); 1__0.5d is invalid decimal "1__0.5d". An exponent is not allowed.

Taught in Scalars & Strings.

A string literal is a String. Every form, raw and typed ones included, holds UTF-8 text: a byte in its body that is not part of a UTF-8 sequence is a compile error, and no escape writes one.

A quoted string, "...", is one line. It reads these escapes and no others:

EscapeCharacter
\n \r \tnewline, carriage return, tab
\\ \"backslash, quote
\u{1F600}the Unicode scalar value with that hex number: 1 to 6 digits in braces, at most 10FFFF, not a surrogate (D800 to DFFF)
\${a literal ${

Any other backslash sequence is a compile error: \q is invalid escape \q, a \u without braces is \u escape requires braces, e.g. \u{1F600}, \u{} and seven digits are invalid \u{...} code point: 0000041; a \u{...} escape takes 1 to 6 hex digits, and \u{110000} and \u{D800} name the limit they break. There is no \0 and no \'.

${expr} interpolates the value of expr, which runs when the string is built. Interpolation calls Display.to_string on the value, so its type must implement Display (§12); "${Unit}" is no impl of `Display` for `Unit` (required via call site). A $ not followed by { is text ($5, $$), and $${n} is a $ followed by an interpolation. #, #{ and braces are text.

fn main()
    name = "Ada"
    dbg "Hello, ${name}!"            // "Hello, Ada!"
    dbg "\${HOME}" == "$" + "{HOME}" // True
    dbg "costs $5"                   // "costs $5"
end

A triple-quoted string, """...""", spans lines. It reads no escapes, so a backslash is text, except \${, which writes ${. It interpolates as a quoted string does. Its body is cut by three rules, in order:

  1. A newline right after the opening """ is removed.
  2. The baseline is the least leading whitespace of every line that is not blank and of the closing """ line. That much is removed from the start of each line. A blank line loses whatever leading whitespace it has, up to the baseline.
  3. The newline right before the closing """ is removed.
fn main()
    sql = """
        SELECT *
          FROM users
        """

    dbg sql // "SELECT *\n  FROM users"
end

A line indented less than the closing """ sets the baseline, and the lines indented more keep the difference.

Taught in Scalars & Strings.

A backtick literal, `...`, is a raw string. Its body is the text as written: no escapes, so every backslash is text, and no interpolation, so ${...} and \${ are text. A raw string that spans lines is cut by the three rules of a triple-quoted string. The body ends at the first backtick, so a raw string cannot hold one.

fn main()
    regex = `\d{3,4}`
    template = `price: ${PRICE}`
    dbg regex                          // "\\d{3,4}"
    dbg template == "price: \${PRICE}" // True
end

A backtick literal with a type prefix is a typed literal (Typed literal forms below).

Taught in Scalars & Strings.

A single-quoted literal holding one ASCII character (U+0000 to U+007F) is a Codepoint, the type of a Unicode scalar value. Its type is std’s Codepoint whatever the file has in scope, and Codepoint is in the prelude.

fn main()
    dbg Codepoint.to_int('a')  // 97
    dbg Codepoint.to_int('\n') // 10
    dbg Codepoint.to_int('\'') // 39
    dbg Iter.count('a'..='z')  // 26
end

A codepoint literal is ASCII only because above U+007F one character can be one codepoint or several (é precomposed or decomposed), and a literal would have to pick one. Text is a String ("é"); another scalar value comes from Int.to_codepoint.

  • It is not text: "a" == 'a' is equality type mismatch: String vs Codepoint.
  • It compares, orders and hashes as a Codepoint, and a range of codepoints iterates.
  • It is a pattern (§10). A case on a Codepoint whose arms test literals needs a _ arm. There are no range patterns.

A printable ASCII character is written as itself, except ' and \, which are '\'' and '\\'. A control character (U+0000 to U+001F, U+007F) must be escaped. The escapes are \n, \r, \t, \\, \' and \u{...} (1 to 6 hex digits, at most 7F). There is no \0 (write '\u{0}'), and \" is an error (write '"').

These are compile errors, each naming the literal: an empty '' (empty codepoint literal ''; a codepoint literal holds exactly one ASCII character), more than one character (codepoint literal 'ab' holds more than one character; write "ab" as a string), a character above U+007F ('é', whose message suggests "é" or Int.to_codepoint), a control character written directly, an unknown escape, and a literal with no closing quote on its line.

Taught in Collections.

A named struct is built by its name, with the { against it: Point{x: 1}, as a variant (Some(1)) or a distinct type (UserId(5)) is built by its name. A named tuple, a distinct type over a tuple, is built by its name with the elements as arguments: Pair(1, "x"). A tuple is its parentheses with a comma inside, (1, "x") (§4 Tuples). A { always begins data (§2 Bodies).

Collection literals have no symbol. Brackets, [...], are a list, a vector or a set; braces, {...}, are a map or a struct. A type built on a collection writes its name in front of the bracket or brace, and so may the std collections themselves: Vector[1, 2], Set["a"].

ShapeUnnamedNamedPattern
struct{x: 1}, {x:}Point{x: 1}, geo.Point{x: 1}, Shape.Circle{radius: 1.0}, .Circle{radius: 1.0}{x:, y:}, Point{x:, y:}, .Circle{radius:}
tuple(a, b)Pair(1, "x")(a, b), Pair(a, b)
list[1, 2], []Ids[1, 2], .Items[1, 2][first, ..rest], [a, b]
vector[1, 2], [] where one is expectedVector[1, 2], Path[1, 2], .Steps[1, 2][first, ..rest], [.., last], Path[a, ..]
set[1, 2], [] where one is expectedSet[1, 2], Tags["a"], .Tagged["a"]["admin", ..rest], [1, 2]
map{"k" => v}, {}Kvs{"k" => 1}, Json.Obj{"k" => v}, .Obj{"k" => v}{"k" => v}, {}, Kvs{"k" => v}

Which collection an unnamed bracket literal is comes from its position, as the struct a brace literal with no name builds does:

  • Where the expected type is a Vector<T> or a Set<T>, [...] is that collection, its elements checked against T. Where it is a distinct type over a list, vector or set (type Path Vector<Int>), [...] builds that type, its elements checked against the collection it wraps; an opaque distinct type is built so only in its own file. Anywhere else, a List<T> or an Iter<T> expected or no type at all, it is a list.
  • With no collection expected, a literal with spreads is the collection its first spread with a type of its own is, when that is a vector or a set: with v: Vector<Int>, [..v, 4] is a Vector<Int>. A spread that is any other Iter leaves it a list.
  • An expected type reaches a literal wherever one reaches a dot-leading variant (§4 Variant Resolution): an annotated binding, an argument (a generic one included: Vector.length([1, 2]) takes a vector), a field, a return value, an element of an enclosing literal, and the other operand of ==, !=, + and -.
  • Vector[...] and Set[...] name the collection where no position fixes it. List[...] and Map{...} are allowed and never needed ([...] and {...} are those already).

The first entry of a brace literal says which it is: name: opens a struct, key => a map, and the entries that follow must agree. {} is the empty map, or the empty value of the map type expected; an anonymous struct has at least one field, so {} is never one. A struct update’s spread comes first and its fields after ({..base, x: 1}); a brace holding one spread and nothing else is a struct update, and one holding two or more spreads a map. Name{} is what the name declares: Point{} a struct built from its field defaults, Kvs{} the empty map of a type over one.

  • A struct literal names every value it gives. A value with no name is an error, never a field by position, so reordering a struct’s fields cannot swap two values of one type: Student{&1.first, &1.second} is a struct literal names its fields; write `Student{name: &1.first, score: &1.second}`, whose fix writes the names in declaration order. When the values do not fit the fields, the error counts them and names the fields instead.
  • A named literal always builds the type it names, never the underlying shape: Ids[1, 2] is an Ids even where a List<Int> is expected, where it is a type mismatch. A name that names no type is an error, and so is a name of a type over no list, vector or set before a bracket: Point is not a type over a list, vector or set; `Point[...]` requires `type Point List<T>`, `Vector<T>` or `Set<T>`.
  • A capitalized name is always a type or a variant (§2 Naming Conventions), so Name[ always opens a literal; Nomi has no indexing syntax.
  • A field is written name: value. A field whose value is a binding of its own name is punned, name:, which is name: name; the name alone is no field. P{a} is a field is written `a: value`, or `a:` for `a: a`, with the help write `P{a:}`.
  • A name followed by a { on its line opens a struct or map literal or pattern, in an if or case head as anywhere else: case Point{x: 1}, if p == Point{x: 1} then.
  • A payload variant and a distinct type over a scalar are calls, not literals: Some(1), .Circle(2.0), UserId(5).
  • Map keys are expressions: {key => 1} reads the binding key, and a string key is quoted.
  • # and % write no literal. #[1, 2] is a vector is written without `#`: `[1, 2]` where a Vector is expected, else `Vector[1, 2]`, %[1, 2] the same for a set, %{"k" => 1} is a map is written without `%`: `{key => value}`, and #Path[1] or %Kvs{...} is a literal or pattern naming its type is written without `#`: `Name[...]`, `Name{...}` (or %); each fix drops the symbol, or writes Vector or Set for it. After an operand, % is the remainder operator.
  • Types are written without a symbol, except a tuple’s and an anonymous struct’s: Vector<T>, Set<T>, Map<K, V>, (Int, Int), {x: Int}. A { where a type is expected always opens an anonymous struct type.

An empty literal takes its element types from the expected type. With none, its binding needs an annotation (§5 Locally-determined bindings and turbofish).

A literal evaluates its parts from left to right, each once.

Taught in Collections.

..e inside a literal is a spread: the literal holds the parts of e. A list, vector, set or map literal takes any number of spreads, anywhere among its elements, and is its parts joined in the order written:

  • A list’s and a vector’s parts are concatenated, and a set’s are unioned.
  • A map’s parts apply left to right: a later key replaces an earlier key’s value and keeps the earlier key’s position. So {"a" => 0, ..m} is m with a default for "a", and {..m, "a" => 0} is m with "a" replaced.
fn main()
    xs = [2, 3]
    dbg [1, ..xs, 4] // [1, 2, 3, 4]
    s: Set<Int> = [1, 2]
    dbg [..s, 3] // Set[1, 2, 3]
    defaults = {"theme" => "light", "font" => "mono"}
    dbg {..defaults, "theme" => "dark"} // {"theme" => "dark", "font" => "mono"}
end

A spread in a list, vector or set literal is any Iter of the literal’s elements: a collection, a Maybe (zero or one element), a Range, a lazy Iter chain, or a type with an impl Iter. Its elements join in the order it hands them out. A spread that is no Iter is list spread `..` requires an Iter of the list's elements, got Int (or vector, set), and one of other elements is list spread element type mismatch: Int vs String.

A bracket literal with no expected type is the collection its first spread with a type of its own is, when that is a vector or a set (§3 Literal forms). A list literal with no expected type takes its element type from its first spread whose value has a type of its own (not a literal, and not a form that takes its type from its position), and its elements are built as that type, as they are under an annotation (§5 Type argument conversion): with routes: List<(Route, Handler)>, [(Route`GET /`, home), ..routes] is a List<(Route, Handler)> though home is a (Request) -> Response.

A map spread is a map. Each spread must be a Map<K, V> (map spread `..` requires a map, got Point), all of one type (map spread type mismatch: expected Map<String, Int>, got Map<Int, Int>), and the first spread’s type is the literal’s. Each entry’s key must be a K and its value a V, with the coercions any map literal’s entries get from an expected type: map spread key type mismatch: expected String, got Int (or value). A base whose types are still open, such as {}, takes them from the entries. An entry may repeat a key of a spread; two equal constant keys among the literal’s own entries are the error of Repeated keys.

A vector, set or map literal of one spread of its own type and nothing else is that spread: [..s] with s a set is a set spread with no elements is its base value; write `s` (or vector, map ... with no entries). A lone spread of another Iter, Set[..maybe] or Vector[..iter], builds the collection from it.

The spreads are evaluated first, from left to right, then the elements from left to right. Each expression runs once.

A spread has no named form, since the base already carries the type: Kvs{..base, "a" => 1} is map spread `..` has no named form; write `{..base, key => value}` — the spread head carries the type, and Path[..base, 1] is spread `..` has no named form; write `[..base, item]` — the spread head carries the type. The std collections’ own names are the exception, since a spread of another Iter fixes no collection: Vector[..iter, 1], Set[..maybe].

A struct literal takes one spread, first: that is a struct update (§4 Struct Updates). At a field or key of an update a spread may be a bare .., the value already there (§4 Struct Updates).

Map keys are evaluated at run time, so two entries of one literal can have equal keys. The map holds that key once: the later entry’s value wins, and the key keeps the earlier entry’s position.

fn main()
    x = 1
    y = 1
    dbg {x => "a", 2 => "c", y => "b"} // {1 => "b", 2 => "c"}
end

When two keys are the same constant, the earlier entry can never be read, so the literal is a compile error at the second key: key `0x1` is given twice in this map literal; the later entry would replace the earlier. A constant is a value whose equality to another constant is certain at compile time:

  • an Int, Float, Decimal, String or Codepoint literal, or a negated number literal, compared by value: 255 and 0xFF are one key, 1.0 and 1.00 are one, 0.0 and -0.0 are one, and 1.0d and 1.00d are one;
  • True and False;
  • a variant with no payload (None, Direction.North, .North), or a variant constructor applied to constants (Some(1)), when the enum has no impl Equatable of its own, written or derived, and std declares none;
  • a tuple of constants ((1, "a")).

Any other key, a variable, a call, a struct or a value of a type with its own impl Equatable, is never compared at compile time. The same rule holds for a set literal (Set[1, 2, 1], or [1, 2, 1] where a set is expected, is element `1` is given twice in this set literal; a set holds it once) and for a map pattern (key `"k"` is given twice in this map pattern; match its value once). Set elements equal only at run time make one element:

fn main()
    x = 1
    y = 1
    dbg Set[x, y] // Set[1]
end

Taught in Collections.

a..b is a half-open range and a..=b a closed one. Both operands must have the same Comparable type, and the literal is a Range<T> (§4 Built-in Types). A subtype and its ancestor join as a branch does, and a range with no type written for it ranges over the base (§4 Chains and conversion): 0..List.length(xs) is a Range<Int>. An empty collection literal in one operand, whole or inside a tuple or list, takes its element type from the other: [1]..[] is a Range<List<Int>>. Both bounds are required: ..5, 5.. and .. are not ranges, since .. alone is a spread.

A range over a type that implements Discrete (Int, Codepoint) is an Iter of its values, lazy, with no list built. A range over any other type (String, Float, Decimal) is an interval, used for membership.

Discrete and Steppable<S> are the prelude interfaces behind this. Discrete.next(v) returns the value after v, or None past the last, and a range of a Discrete type walks its values with it. Steppable<S>’s step_by(v, by) moves v by a step of type S, and Range.step_by walks a range of a Steppable type by a step the caller gives, as Range.step_by(0d..1d, 0.25d) does for Decimal. std::discrete and std::steppable list their implementors.

fn main()
    dbg Iter.to_list(1..5)     // [1, 2, 3, 4]
    dbg Iter.to_list(1..=5)    // [1, 2, 3, 4, 5]
    dbg 3 in 1..5              // True
    dbg "h" in "a".."m"        // True
    dbg 1.50d in 1.25d..=2.50d // True
    dbg Iter.to_list(5..1)     // []
end

Reversed bounds give an empty range. An unbounded range comes from Range.from(n), of n’s type, or Range.naturals(), and a step from Range.step_by (std::ranges). A range’s parts are Range.start(r), Range.stop(r) (its end, None when unbounded) and Range.is_inclusive(r).

The prelude holds three subtypes of Range<T> (§4 Generic subtypes). NonEmptyRange<T> is a range that holds a value, Range.contains(r, Range.start(r)): a..b with a < b, a..=b with a <= b, or an unbounded range. ClosedRange<T> is a NonEmptyRange that holds its end or has none, a..=b or Range.from(n), and BoundedRange<T> is a NonEmptyRange with an end. A function whose two bounds must agree takes one of them, so a literal written backwards is an error when the program is compiled, with the rule that is false: this ClosedRange<Int> literal breaks the rule of NonEmptyRange<Int>, a supertype of it: `fn r -> Range.contains(r, Range.start(r))` is false. Comparable.clamp(value, 0..=11) takes a ClosedRange (§5), random’s Generator.int(1..=6) takes a BoundedRange, and Generator.float(0.0..1.0) takes a FiniteRange, a bounded range whose ends are finite. Range.from(n) and Range.naturals() are ClosedRanges: where a ClosedRange<NonNegativeInt> is expected, Range.from(2) is one, and its literal 2 is checked as a NonNegativeInt when the program is compiled. A Float range with a NaN end holds no value, since no Float is <= NaN, so it is none of the three.

.. binds tighter than comparison and the pipe, and looser than arithmetic: 1 + 2..5 + 6 is (1 + 2)..(5 + 6).

Taught in Typed Literals.

A string literal with a type name written against its opening delimiter is a typed literal: Date"2026-05-04", Sql"""...""", Regex`\d+`. The name is PascalCase, with no space before the delimiter. A lowercase name against a string is a name followed by a string, which is an error. What a typed literal means, and when its handler runs, is §18. The delimiters differ only in escapes and interpolation, as for an untyped string: a quoted body reads escapes and ${...} slots, a triple-quoted one reads slots and no escapes, and a backtick body is raw text with no slots. A literal without slots is checked at compile time in any of the three, and a failure is a compile error at the literal.

// quoted: escapes and slots
Date"2026-05-04"

// triple-quoted: slots, no escapes
Date"""
2026-05-04
"""

// backtick: raw text
Regex`\d{3,4}`