Skip to content

Scalars & Strings

Nomi has three number types: Int, Float and Decimal. The other basic types are Bool, String, and Byte and Bytes for binary data. The chapter ends with regular expressions, which the String functions take for finding, splitting and replacing text.

fn main()
    dbg 42 + 8
    dbg 10 - 3
    dbg 2 * 21
    dbg 7 / 2
    dbg 7 % 2
    dbg -(3 + 4)
    dbg 42 > 10
    dbg True and not False
    dbg Int.pow(2, 100)
    dbg 0b1011 >>> 1 &&& 1 // the second-lowest bit
    dbg 0b0011 ||| 0b0100  // set a bit
end

Arithmetic and comparisons work as in most languages. The logical operators are and, or and not. not binds looser than a comparison, so not a == b is not (a == b). An Int is a whole number of any size, so arithmetic never overflows. / on Int drops the remainder, rounding toward zero, and % gives the remainder. Their divisor is a NonZeroInt, so a division by zero does not compile.

The bitwise operators are &&&, |||, ^^^, prefix ~~~, <<< and >>>. &&& and the shifts bind like *, and ||| and ^^^ like +.

Each arithmetic operator comes from an interface: + from Add, - from Subtract, * from Multiply and / from Divide. The number types implement them. Your own types can implement them too, when an operator is the clearest way to write the operation.

Fine print

  • % takes the sign of the dividend: -7 / 3 is -2 and -7 % 3 is -1. Int.modulo is the floored form: Int.modulo(-7, 3) is 2.
  • n / d with d an Int is `/` divides by a NonZeroInt; `d` is an Int: check it first (if d == 0 then ...) or take a NonZeroInt. A non-zero literal (n / 2) passes, and so does a value whose range rules zero out, such as each d in 1..=n |> Iter.filter(fn d -> n % d == 0). The shift count of <<< and >>> is a NonNegativeInt the same way. Float division by zero gives an infinity or NaN instead (see Exact arithmetic with Decimal).
  • The number types never mix. 1 + 2.0 is the error `+` needs two values of one type, and these are Int and Float, whose help says to write 1.0; convert a value with Int.to_float or Float.to_int, which is None for NaN and the infinities.
  • % works on Float and Decimal too, with the dividend’s sign: -7.5 % 2.0 is -1.5, and 1.0 % 0.0 is NaN.

Spec: Integer division and remainder, Integer arithmetic is exact, No Implicit Conversion.

fn main()
    dbg 1_000_000
    dbg 0xFF
    dbg 0b1010
    dbg 1.0e10
end

A number can use _ to separate digits. 0x starts a hexadecimal number, 0b a binary one, and 0o an octal one. e writes a number in scientific notation.

fn main()
    // Float carries base-2 imprecision
    dbg 0.1 + 0.2 == 0.3

    // Decimal is exact
    dbg 0.1d + 0.2d == 0.3d

    // Sum four prices
    dbg 19.99d + 5.00d + 2.50d + 0.99d
end

Float is fast but not exact. It stores numbers in binary, so 0.1 + 0.2 is not quite 0.3. To compare a computed Float, give the difference you accept: Float.equal_within(0.1 + 0.2, 0.3, 1e-9) is True. The tolerance is a NonNegativeFloat, so a negative literal there fails to compile.

A Float follows IEEE 754, so dividing by zero doesn’t stop the program: 1.0 / 0.0 is +Inf, and 0.0 / 0.0 is NaN, which Float.is_nan detects.

Decimal stores numbers in base 10 and adds them exactly. Use it when a rounding error would be a bug, as with money. A decimal literal ends in d.

Decimal’s +, - and * are exact. / keeps 34 significant digits, rounded half-even, so 10d / 3d is 3.333333333333333333333333333333333d, and a quotient that ends is exact with no trailing zeros: 10.00d / 4d is 2.5d. To round to a number of places, name them and the rounding: Decimal.divide(10d, 3d, 2, .HalfEven) is 3.33d.

Fine print

NaN compares three ways, chosen so maps, sorting and patterns behave:

  • == is reflexive: nan == nan is True, so a NaN map key is found again. -0.0 == 0.0 is True, and the two are one key.
  • Float.compare is a total order with NaN highest, so a sort is deterministic: Float.compare(nan, nan) is Equal.
  • <, <=, > and >= follow IEEE 754: nan <= nan is False.

Decimal has no NaN or infinity, and its divisor is a NonZeroDecimal. Its scale shows in display but not in equality: 1.50d == 1.5d.

Spec: Float Special Values, NaN and the three comparison behaviours, Decimal arithmetic.

import std::io

fn main()
    name = "Nomi"
    io.print("Hello, ${name}!")
    io.print("1 + 2 = ${1 + 2}")
    io.print("Hello" + ", " + "Nomi")
end

${expr} inside a string inserts the value of expr. + joins two strings, because String implements Add.

Interpolation turns each value into text with Display.to_string. io.print accepts any value that implements Display. So you rarely convert a value to a string yourself before printing it.

A backslash starts an escape: \n, \r, \t, \\, \" and \u{1F600}, a character by its Unicode number. To write a literal ${, write \${. A $ on its own is ordinary text:

import std::io

fn main()
    io.print("echo \${HOME} costs $5")
end

To split text:

The String reference lists the rest, and Regular expressions below shows how to split and search by a pattern.

Nomi looks at text at four levels:

  • A String is text. There is no separate Char type, so a single character is a String too.
  • A grapheme is one character as a reader sees it. é and many emoji are one grapheme even when Unicode builds them from several code points. Nomi represents a grapheme as a String.
  • A Codepoint is one Unicode code point: a number Unicode assigns to a character. Use it when you need the numbers that make up text.
  • Bytes is immutable binary data, and a Byte is one byte of it. Use it for UTF-8 encoding, file and network data, and Go’s []byte when calling Go.

Most string functions count graphemes. String.length, String.slice and String.reverse work in characters as a reader sees them, not in bytes. Iterating over a String also gives its graphemes, so Iter.to_list("café") is a list of four strings.

String.to_codepoints gives the code points instead:

fn main()
    dbg String.length("café")
    dbg Iter.to_list("café")

    "café"
    |> String.to_codepoints()
    |> Iter.map(Codepoint.to_int)
    |> Iter.to_list()
    |> dbg
end

An ASCII character in single quotes is a Codepoint literal: 'a'. Escapes work too: '\n', '\'', '\u{7F}'. It is a Codepoint, not a string, so "a" == 'a' is a type error.

Use codepoint literals for work such as scanning and matching characters, and keep text in strings. They are limited to ASCII because only there are the character, its code point and its UTF-8 byte the same thing. 'é' is an error; write "é" as a string.

fn kind(cp: Codepoint) -> String
    case cp
        ',' -> "comma"
        ' ' -> "space"
        _   -> Codepoint.to_string(cp)
    end
end

fn main()
    "a, b"
    |> String.to_codepoints()
    |> Iter.map(kind)
    |> Iter.to_list()
    |> dbg
end

To classify a codepoint, ask Codepoint: is_letter, is_whitespace, is_upper and is_lower follow Unicode, so é and ж are letters. is_digit and to_digit accept only ASCII 0 to 9, which is what a phone number or a checksum means.

fn main()
    text = "Tél 555-01"

    text
    |> String.to_codepoints()
    |> Iter.filter(Codepoint.is_letter)
    |> Iter.map(Codepoint.to_string)
    |> String.join()
    |> dbg

    text
    |> String.to_codepoints()
    |> Iter.map(Codepoint.to_digit)
    |> Maybe.values()
    |> Iter.to_list()
    |> dbg
end

== compares strings byte by byte. The same visible text can be stored in more than one Unicode form, and two such strings are not equal. Before comparing text from different sources, put both in the same form with String.normalize.

Fine print

  • A grapheme can be many code points. The family emoji 👨‍👩‍👧 is one grapheme of five code points, so String.length counts it as 1.
  • Ordering compares bytes too, which is code point order. For the order a reader expects, use std::collation.
  • A Codepoint literal holds one ASCII character. Outside ASCII, take one from String.to_codepoints or build it with Int.to_codepoint.

Spec: Strings, Codepoint literals.

import std::io

fn main()
    raw = String.to_bytes("café")
    dbg Bytes.length(raw)
    dbg raw |> Iter.map(Byte.to_int) |> Iter.to_list()

    prefix = Bytes.from_list([0x67, 0x6F, 0x3A])

    case Bytes.to_string(prefix + raw)
        Ok(text)    -> io.print(text)
        Err(reason) -> io.print(reason)
    end
end
  • String.to_bytes encodes text as UTF-8. é takes two bytes, so café is 5 bytes.
  • Bytes can be iterated, so the Iter functions work on it.
  • Byte.to_int turns a Byte into an Int.
  • + joins two Bytes values, as Bytes.concat does.
  • Bytes.to_string decodes UTF-8 and returns a Result, since the bytes may not be valid UTF-8.

A Byte is not a number, so you can’t do arithmetic on it. Convert with Int.to_byte and Byte.to_int when you need the number. An integer literal where a Byte is expected is one, so [0x67, 0x6F, 0x3A] above is the bytes of go:, and a literal outside 0 to 255 there is a compile error.

Fine print

  • Only the literal takes its type from where it stands. n = 0x81 is an Int, and b: Byte = n is type mismatch: expected Byte, got Int.
  • In a comparison or a bitwise operator, a literal takes Byte from the other operand: b == 0x41, b &&& 0x7F.
  • A Byte pattern is a literal too: 0x00 -> "nul".

Spec: Byte literals.

import std::io

fn main()
    name = "Alice"

    query = """
        SELECT *
        FROM users
        WHERE name = '${name}'
        """

    io.print(query)
end

A string in """ quotes can span several lines. Interpolation works as usual. The indentation that every line shares is removed.

import std::io

fn main()
    pattern = `\d{3,4}`
    template = `price: ${PRICE}`

    query = `
        SELECT *
        FROM invoices
        WHERE total > ${MIN_TOTAL}
        `

    io.print(pattern)
    io.print(template)
    io.print(query)
end

A string in backticks is raw. Backslashes and ${...} are kept as written. Use it for text that contains those characters. A raw string can span several lines, and its shared indentation is removed the same way.

Fine print

  • A raw string has no escapes at all, so it can’t hold a backtick: the first backtick ends it.
  • A triple-quoted string reads no escapes either, except \${, but it still interpolates ${...}.
  • In both multi-line forms, a newline right after the opening quote and right before the closing one is dropped, and the closing line’s indentation counts toward the shared indentation.
  • A backtick string with a type in front, as in Regex`\d+` , is a typed literal (Typed Literals).

Spec: Raw strings, Triple-quoted strings.

std::regex has Regex. Write a pattern in backticks, as Regex`\d+` , so its backslashes stay as written. The compiler checks the pattern, so Regex"[" is an error before the program runs (Typed Literals explains how).

String.split, String.contains, String.starts_with, String.ends_with, String.replace, String.find and String.find_all take a Matcher for the text to look for: a plain String or a Regex. String.find returns the first match and String.find_all every one. String.captures returns the text each group in parentheses matched, shaped by the literal’s type: date below is a Regex<(String, String, String)>, a group a match can skip is a Maybe<String>, and named groups ((?P<year>\d{4})) make a struct. With a Regex, String.replace reads $1, $2 in the replacement as the groups’ text ($$ is a literal $):

import std::regex.Regex

fn main()
    text = "Order 1042 shipped 2026-10-25, order 977 on 2026-10-26"
    date = Regex`(\d{4})-(\d{2})-(\d{2})`

    dbg String.contains(text, date)
    dbg String.find(text, Regex`\d+`)
    dbg String.find_all(text, date)
    dbg String.captures(text, date)
    dbg String.split("a, b,c ,  d", Regex`\s*,\s*`)
    dbg String.replace(text, Regex`\d{3,4} `, "# ")
    dbg String.replace(text, date, "$3/$2/$1")

    dbg String.find_all(text, Regex`(?i)order \d+`)
end

(?i) at the start of a pattern ignores case. A pattern in double quotes, as Regex"\\d+", is checked the same way, but inside double quotes a backslash starts an escape, so the pattern’s \d is written \\d. A pattern with a ${...} slot is compiled when the program runs, so it is a Result that you unwrap with ? or case.

Every example that uses Scalars & Strings

Collections is next. It puts these values into lists, maps and sets.