Skip to content

std::comparable

Import with import std::comparable.

Types

Interfaces

enum Ordering
    Less
    Equal
    Greater
end

Ordering is the result of a three-way comparison: Less, Equal, or Greater. Returned by Comparable.compare(a, b) and by sort callbacks. Pattern-match on it; do not rely on tag-index ordering.

fn chain(first: Ordering, next: Ordering) -> Ordering

type function on Ordering

first, unless it is Equal; then next. Chains two comparisons into one, so a comparator orders by one key and breaks ties with a second, each in its own direction: below, points descending (the arguments swapped), then name ascending. Both comparisons run; for keys that all sort the same way, a tuple key (Iter.sort_by(rows, fn r -> (r.team, r.name))) says the same thing and compares the second key only on a tie.

import std::int.Int
import std::iter.Iter
import std::strings.String

assert Ordering.chain(Ordering.Less, Ordering.Greater) == Ordering.Less
assert Ordering.chain(Ordering.Equal, Ordering.Greater) == Ordering.Greater

rows = [("ann", 3), ("bob", 6), ("cy", 3)]

ranked =
    rows
    |> Iter.sort_with(fn (a, a_points), (b, b_points) ->
        Ordering.chain(Int.compare(b_points, a_points), String.compare(a, b))
    end)

assert ranked == [("bob", 6), ("ann", 3), ("cy", 3)]

impl Debug for Ordering

fn inspect(value: Ordering) -> String

impl Debug.inspect

impl Display for Ordering

fn to_string(value: Ordering) -> String

impl Display.to_string

impl Variants for Ordering

fn variants() -> List<Ordering>

impl Variants.variants

enum Direction
    Ascending
    Descending
end

Direction selects ascending or descending order along a Comparable type. Used as a modifier on sort APIs (Iter.sort, Iter.sort_by) that don’t take an explicit comparator. For custom orderings, use Iter.sort_with and encode the direction directly in the (T, T) -> Ordering callback.

impl Debug for Direction

fn inspect(value: Direction) -> String

impl Debug.inspect

impl Display for Direction

fn to_string(value: Direction) -> String

impl Display.to_string

interface Comparable
    fn compare(a: self, b: self) -> Ordering
    fn min(a: self, b: self) -> self
    fn max(a: self, b: self) -> self
    fn clamp(value: self, range: ClosedRange<self>) -> self
end

Comparable is the total-ordering protocol. compare(a, b) must return Less when a < b, Greater when a > b, and Equal when they are equal under the type’s notion of equality (which should agree with Equatable.equal).

<, <=, > and >= call Comparable.compare(a, b) and match on the Ordering. They need a declared impl: on a type with no Comparable impl they are a compile error. == compares a type with no impl structurally, but ordering has no structural meaning, so a type declares it with derive Comparable or a hand-written impl.

Int, Float, Decimal, Bool and String implement Comparable. Int and Decimal use numeric order. Bool orders False < True. String compares its UTF-8 bytes. Float.compare is a total order in which NaN equals NaN and is greater than every other Float; the operators on Floats follow IEEE 754 instead, where every ordering comparison with NaN is False.

derive Comparable synthesizes a lexicographic compare for structs (field-by-field in declaration order), enums (variant-tag-then-payload), and distinct types (delegating to the inner value).

A tuple is Comparable when every element is, lexicographically: the first elements decide unless they are Equal, then the second, and so on. That makes a tuple the key for a sort by several fields, Iter.sort_by(rows, fn r -> (r.team, r.name)). To sort one of the keys descending, negate a number in the key ((-r.points, r.name)), or wrap any Comparable key in Reverse.of from std::reverse ((Reverse.of(r.name), r.points)).

Every Comparable type also has min, max and clamp, written once here over compare: Int.min(a, b), Date.clamp(day, first..=last), or Comparable.min(a, b) in a function generic over a T: Comparable.

import std::calendar.Date
import std::duration.Duration
import std::int.Int
import std::iter.Iter
import std::maybe.Maybe.Some
import std::strings.String

assert (1, "b") < (2, "a")
assert (1, "a") < (1, "b")
assert Iter.max([(1, "z"), (2, "a")]) == Some((2, "a"))

rows = [("cy", 3), ("bob", 6), ("ann", 3)]
by_points = Iter.sort_by(rows, fn (name, points) -> (-points, name))
assert by_points == [("bob", 6), ("ann", 3), ("cy", 3)]

assert Int.min(3, -2) == -2
assert Int.max(3, -2) == 3
assert Int.min(-Int.pow(10, 30), 1) == -Int.pow(10, 30)
assert Int.clamp(15, 0..=10) == 10
assert Int.clamp(-3, 0..=10) == 0
assert Int.clamp(7, 0..=10) == 7
assert Int.clamp(-3, Range.from(0)) == 0
assert String.min("pear", "apple") == "apple"
assert String.clamp("zebra", "a"..="m") == "m"
assert Duration.max(Duration.seconds(90), Duration.minutes(1)) == Duration.seconds(90)

assert Duration.clamp(Duration"5s", Duration"30s"..=Duration"5m") == Duration"30s"

assert Date.min(Date"2026-03-01", Date"2025-12-31") == Date"2025-12-31"
assert Date.clamp(Date"2027-01-01", Date"2026-01-01"..=Date"2026-12-31") == Date"2026-12-31"
assert Comparable.max((1, "b"), (1, "a")) == (1, "b")
fn compare(a: self, b: self) -> Ordering

interface Comparable

fn min(a: self, b: self) -> self

interface Comparable

The lesser of a and b by compare; a tie returns a. Float overrides it with IEEE 754’s minimum, where NaN wins.

fn max(a: self, b: self) -> self

interface Comparable

The greater of a and b by compare; a tie returns a. Float overrides it with IEEE 754’s maximum, where NaN wins.

fn clamp(value: self, range: ClosedRange<self>) -> self

interface Comparable

value held to range, a ClosedRange: its start when value is below it, its end when above, else value. A range unbounded above, Range.from(n), clamps only below. The range is a ClosedRange, so a backwards range (10..=1) or one whose end it leaves out (0..10) is an error when the program is compiled, and a range computed when it runs goes through ClosedRange.try_from. Float overrides it so that a NaN value stays NaN.