5. Type relations
Type identity
Section titled “Type identity”A declared type’s identity is its declaring file and its name. Two files may
each declare a Point, and the two are different types. A struct, an enum
and a distinct type are each distinct from every other type, their
representation included.
A tuple type and an anonymous struct type are structural: two of the same
shape are one type (§4 Built-in Types). A function type is structural. A
typealias is another spelling of its target and adds no type (§4 Type
Aliases). A generic type’s instances are the same type exactly when their
type arguments are.
Assignability
Section titled “Assignability”A value of type S may stand where type T is expected when:
SandTare the same type;Tis an interface thatSimplements, and the value becomes an interface value (§12);Tis an interface conjunctionA and Bwhose every memberSimplements, or thatS, itself a conjunction or an interface, holds every member of (§12 Interface conjunctions);Tis an enum that embedsS(§4 Embedded Types), at the top or at any position that converts (Covariant conversion);Sis a subtype andTis one of its ancestors, its base included (§4 Subtypes), orTis a subtype with no rule of its own whose every parentSconverts to, at the top or at any position that converts; and whereTis an interface,Sconverts to it as its base does;- both are function types and
SfitsTby the rule below; - both are one generic type, tuple, record or function type, and
Sconverts toTpart by part (Covariant conversion).
There is no other implicit conversion (No Implicit Conversion).
A tuple’s elements and a record’s fields convert as the value does:
(1, p) is a (Int, Named) when p’s type implements Named. Iter
takes its element by the same rule as the top, since an Iter only hands
its elements out: a List<Int> passes where an Iter<Display> is
expected, and a List<List<Int>> where a List<Iter<Int>> is.
A function of type (P1) -> R1 fits where (P2) -> R2 is expected when
each P2 fits its P1 and R1 fits R2: parameters are contravariant and
results covariant. The two take the same number of parameters, except a
function whose parameters past the expected ones have defaults (§7 Default
Arguments) and the callback of a stateless Iter.loop (§13 loop). Inside a function type, one type fits another as a value
does: when they are the same, when a concrete type meets an interface it
implements, when a type meets an enum that embeds it, when both are
function types that fit, or when both are one generic type whose type
arguments convert (Covariant conversion): a (Int) -> List<Int> fits
where a (Int) -> List<Display> is expected. The rule holds at every
position a function value flows into,
a tuple’s element and a record’s field among them: ("a", f) is a
(String, (Int) -> Display) when f is an (Int) -> Int.
fn shown(x: Display) -> String Display.to_string(x) end fn pair(n: Int) -> List<Int> [n, n] end fn main() f: (Int) -> String = shown // Int fits Display h: (Int) -> Iter<Int> = pair // List<Int> fits Iter<Int> dbg f(1) // "1" dbg Iter.to_list(h(2)) // [2, 2] end
The reverse is an error, since the function would receive a value it does
not accept: fn float_str(f: Float) -> String as a (Display) -> String is
type mismatch: expected (Display) -> String, got (Float) -> String. Where
nothing says which way a value flows (the branches of an if or case, the
elements of an unannotated list, two arguments of one type parameter), two
function types must be the same. A collection literal beside a value of
that collection, as an operand of + or - or beside a spread in a list
literal, is built as the value’s type, which says the way (§8 Arithmetic
operators, §3 Spreads). With
fn pick<T>(c: Bool, a: T, b: T) -> T, pick(c, shown, float_str) is
argument 3: expected (Display) -> String, got (Float) -> String; pass a
lambda of the one type instead: pick(c, float_str, fn x -> shown(x)).
Covariant conversion
Section titled “Covariant conversion”Values are immutable, so a list of Ints may stand where a list of
Displays is expected: nothing can put a String into it through the
wider type. Where a value of type F<A> is expected as F<B>, it converts
when each type argument converts by its parameter’s variance:
- a covariant parameter converts as a value does:
F<A>is anF<B>whenAconverts toB; - a contravariant parameter converts the other way:
F<A>is anF<B>whenBconverts toA; - an invariant parameter compares exactly.
The rule applies again inside each type argument, at any depth.
| Type | Its parameters |
|---|---|
List<T>, Vector<T>, Set<T>, Maybe<T> | T covariant |
Map<K, V>, Result<T, E> | both covariant |
| a tuple, an anonymous record | each item and field covariant |
| a function type | its result covariant, each parameter contravariant |
| a struct, enum or distinct type the program declares | inferred from its fields, payloads or inner type |
Iter<T> | T covariant (§5 Assignability) |
| any other std or host type, any other interface | invariant |
Nothing is written to declare a parameter’s variance. It is read off where
the parameter appears in the type’s fields, its variants’ payloads, or a
distinct type’s inner type (type Ids<T> List<T> is covariant in T): a
parameter that appears only where a value is held (a field, a collection’s
element, a function type’s result) is covariant; one that appears only in a
function type’s parameter is contravariant, and two such flips cancel; one
that appears in both is invariant. A parameter passed to another generic
type takes that type’s variance at the place it is passed, and a recursive
type reads its own. A parameter no field names converts either way and is
treated as covariant.
struct Box<T> item: T end struct Sink<T> take: (T) -> String end struct Cell<T> get: () -> T put: (T) -> Unit end interface Store fn size(s: self) -> Int end struct Memory n: Int end impl Store for Memory fn size(m: Memory) -> Int m.n end end fn shown(d: Display) -> String "<${d}>" end fn opened(open: () -> Result<Store, String>) -> Int case open() Ok(s) -> Store.size(s) Err(_) -> 0 end end fn main() m = Some([1, 2]) wide: Maybe<Display> = m // each List<Int> boxed as a Display bx = Box{item: [1]} b: Box<Display> = bx // Box's T is covariant sink = Sink{take: shown} ints: Sink<Int> = sink // Sink's T is contravariant dbg Maybe.map(wide, shown) // Some("<[1, 2]>") dbg shown(b.item) // "<[1]>" dbg ints.take(5) // "<5>" dbg opened(fn -> Ok(Memory{n: 3})) // 3 end
Cell’s T is invariant, so a Cell<Int> is no Cell<Display>:
c: Cell<Display> = cell is type mismatch: expected Cell<Display>, got Cell<Int>, with help Cell<Int> does not convert to Cell<Display>: Cell's type parameter T is invariant, since Cell's fields both hold a T and take one; build a new Cell<Display> from the value's parts. A contravariant
parameter refused the way it would widen names the conversion it needs:
s: Sink<Display> = floats is Sink<Float> does not convert to Sink<Display>: Sink's type parameter T is contravariant, since Sink's fields only take a T, so it converts only where Display converts to Float. A
collection of functions whose parameter would narrow is refused the same
way: gs: List<(Display) -> String> = fs with fs: List<(Float) -> String>
is List<(Float) -> String> does not convert to List<(Display) -> String>: each function takes only Float, and one of type (Display) -> String may be passed any Display. An element that implements no interface the expected
type holds is named: ys: List<Display> = units is List<Unit> does not convert to List<Display>: Unit does not implement Display. An interface
value converts to no other interface, at any depth.
A Set’s elements and a Map’s keys convert too. Converting one into an
interface value keeps its equality and its hash: a value whose type names
it at run time is the interface value itself, and any other is held with
the static type it had, and compares and hashes by that type’s own
equality (§5 Hashing and keys). Two distinct keys of one type therefore
stay distinct, and the converted Set or Map has the size it had:
with m = Set[Some(1), None], s: Set<Hashable> = m holds two elements,
and Set.contains(s, Some(1)) is True.
A conversion costs nothing when each element already is a value of the
wider type: an Int, Float, Bool or String, a declared struct, a
declared enum with no embeds variant or a declared distinct type entering
an interface it implements is the interface value itself, so a List<Int>
is a List<Display> as it is, whatever its length, and so is a function
whose parameters and result convert that way. Any other conversion is work
proportional to the value: a List, Vector, Set or Map is built
again with each element converted, a Maybe, Result, user enum or struct,
tuple or record is built again with its parts converted, and a function is
wrapped in one that converts its arguments and its result on each call. A
value built where the wider type is expected converts each element as it
is built, with no second pass: ys: List<Display> = [1, Some(2)]. So does
a literal operand of + or - beside a value of the same collection, and
the elements of a list literal beside a spread: [1, Some(2)] + ds and
[1, ..ds] are List<Display>s for ds: List<Display>. The branches of
an if or case whose type is written join as it when each converts to
it: c: List<Display> = if f then ints else words.
Annotations and local inference
Section titled “Annotations and local inference”Taught in Bindings & Expressions.
Type Annotations
Section titled “Type Annotations”A function’s parameters and its non-Unit result are annotated (§7). Inside
a body, types are inferred. An annotation is optional on a binding
(name: Type = value), a once and a lambda parameter. A struct field
always has one. A destructuring pattern takes none.
An annotation on a binding drives inference into the value and is checked
against it: m: Map<String, Int> = {} gives the empty literal its types,
f: (Int) -> Int = fn x -> x + 1 gives the lambda its parameter type, and a
value that cannot have the annotated type is an error. A function type is
written (Args) -> Result.
fn main() m: Map<String, Int> = {} f: (Int) -> Int = fn x -> x + 1 dbg Map.size(m) // 0 dbg f(1) // 2 end
Locally-determined bindings and turbofish
Section titled “Locally-determined bindings and turbofish”Taught in Bindings & Expressions.
The checker infers types as far as it can, but a binding must be locally determined: its type must be readable from its own line, not from how the binding is used later. A binding whose type is wholly unresolved, carrying no concrete type because its only type parameters are unsolved, is an error:
xs = [] // error: List<?> m = {} // error: Map<?, ?> x = None // error: Maybe<?> ch = Channel.buffered(4) // error: Channel<?>
xs = [] is
binding 'xs' type is not locally determined: it has unsolved type parameter(s) — add an annotation (`xs: T = …`) or a type argument (`f<T>(…)`).
A later use never rescues it. The type comes from an annotation, or from
explicit type arguments on a call, written after the callee as its signature
writes them:
xs: List<Int> = [] ch = Channel.buffered<Int>(4) f1 = Some<Int>(42)
A type argument is a type annotation: a name that is no type is
unknown type "Nope" at the name (ident<Nope>(1)). Explicit type
arguments are an ordinary call form, usable on any call.
A binding whose type carries any concrete information is determined, even
with a parameter still open: x = Ok(42) is a Result<Int, ?>, and
n = Some(Ok(42)) a Maybe<Result<Int, ?>>.
The enclosing function’s return type is an expected type only for its
result: its tail, a return, and the arms of a case or if in tail
position. A block’s expected type reaches only its tail: in
a once o: Shape = begin ... end whose body is b = .Circle(2.0) and then
b, .Circle names no enum.
A name a pattern binds, in a case arm, an if Pattern = value, a
destructure or a binding with else, must not have a wholly unknown type
once the file is checked. Ok(z) = Maybe.to_result(None, "none") else return
is
the type of 'z' is not determined: nothing fixes the type the pattern binds it to — annotate the matched value (`v: T = …`) or give a call a type argument (`f<T>(…)`),
unless the else fallback or a later use of z fixes it.
A destructuring binding (a tuple, struct, distinct or variant pattern
followed by =, with or without else, or after assert) holds each name
it binds to the rule a name = value binding is held to, once the file is
checked: a name whose type is wholly unresolved is an error. With
fn read<T>() -> (Box<T>, Bool), (box, _) = read() binds box to a
Box<?>, and is
binding 'box' type is not locally determined: it has unsolved type parameter(s) — give the call a type argument (`f<T>(…)`) or annotate the matched value (`v: T = …`);
(box, _) = read<Visit>() is determined. (a, b) = (None, 1) is the same
error unless a later use of a fixes its type. In a case arm or an
if Pattern = value, a name whose type only contains an unknown part, as a
Maybe that can only be None, is accepted.
Type arguments from the arguments
Section titled “Type arguments from the arguments”A generic call’s type arguments come from its arguments first. The type the
call’s result is expected to have (an annotation, a parameter, a return
position) only fills the type parameters the arguments leave open. The
result then converts to the expected type as any value does (Assignability):
an Int into Display, an Iter<Int> into an Iter<Display>. So a
lambda’s parameter has the type the other arguments give it, not the
interface the binding names:
fn main() x: Iter<Display> = [1, 2, 3] |> Iter.filter(fn n -> n > 1) d: Display = Iter.loop(0, fn i -> if i > 2 then break i else i + 1 end end) dbg Iter.to_list(x) // [2, 3] dbg d // 3 end
filter is called at Int, so n > 1 compares Ints, and its Iter<Int>
is the Iter<Display>. Each argument the arguments alone cannot type still
takes the expected type, for the type parameters its own parameter names
and the arguments before it left open:
- a dot-leading variant, an empty literal,
None, a brace literal with no name, and a constructor or generic function named as a value:c: Maybe<Color> = Some(.Red),xs: List<Int> = Iter.to_list([]); - a lambda whose parameter nothing else types:
f: (Int) -> Int = ident(fn x -> x + 1); - a bracket literal, an
ifor acasepassed where the parameter is a bare type parameter, since the expected type says which collection the literal builds and how the branches join:m: Maybe<Vector<Int>> = Some([1, 2]).
A type parameter the result holds below its top comes from the arguments
by the same rule, and the result converts (Covariant conversion):
Ok(Memory.new()) where a Result<Store, Error> is expected builds a
Result<Memory, Error>, which converts to the Result<Store, Error>, and
with fn boxed<T>(v: T) -> Box<T>, b: Box<Display> = boxed(1) builds a
Box<Int> and converts it. Only a type parameter the result holds at an
invariant position (an invariant parameter of a declared type, a std
struct’s or host type’s argument, an interface’s other than Iter’s)
takes the expected type ahead of the arguments, since a type argument
there never converts: with fn cell<T>(v: T) -> Cell<T>, c: Cell<Display> = cell(1) is a Cell<Display>.
Arguments that give the call a type that does not convert to the expected
one are an error at the call: n: Int = Iter.loop("a", fn s -> if s == "" then s else break s) is type mismatch: expected Int, got String.
A range literal’s endpoints are its arguments in the same way: each is
checked against the element of the Range<T> its position expects, so
c: Range<List<Int>> = []..[] is a range of List<Int>s, where with no
annotation the two empty lists settle nothing.
Determined type arguments
Section titled “Determined type arguments”A call must determine every type argument its function makes values of, wherever the call stands. A function makes values of a type parameter when:
- its signature mentions the parameter inside a function type; or
- a parameter’s type holds the type parameter as a type argument of a type
argument (
Iter<Result<T, E>>holdsTthat deep), and its result holds the type parameter in a collection (Result<List<T>, E>).Result.collectis such a function; or - the parameter’s bound declares a function that takes no value of the type
(
Iter.sum’sSummablehasempty_sum()). A bound whose every function takes a value of the type, such asComparable, makes none.
A call’s own result is a value too: a function whose result is the type
parameter itself makes a value of it, and so does a ! or ? that
unwraps the parameter out of the call’s Maybe or Result. Discarding
the value or only printing it does not change that.
A type argument nothing in the enclosing declaration fixes is an error at the argument that carries it:
dbg Result.collect([]) // error: the element type of `[]` is not determined dbg Maybe.collect([None]) // error: the type argument T of `Maybe.collect` is not determined dbg Iter.sum([]) // error: the element type of `[]` is not determined _ = Vector.get([], 0)! // error: the element type of `[]` is not determined
An unsolved type argument that no value has is not an error: the element of
an empty collection (dbg [], Iter.to_list([]), List.first([]),
dbg Vector[], and Iter.sum([[]]), whose T is a List and whose sum is
[]) or the variant a value is not (Ok(1)’s error type). The fix is an annotation on the empty value or
explicit type arguments (Result.collect<Int, String>([])).
Lambda parameter types
Section titled “Lambda parameter types”A lambda parameter with a default and no annotation takes its default’s
type, by the rule for a function’s parameter (§7 Parameter types from
defaults): add = fn a: Int, b = 1 -> a + b needs no other annotation.
Where the lambda’s position also expects a function type, the two must
agree: passed where a (Int) -> Int is expected, fn x = "a" -> 1 is
default value for parameter 'x' is String, expected Int.
A lambda parameter with no annotation and no default takes its type from the
function type its position expects: a parameter’s type at a call, a
function-typed annotation, a declared return type, or a generic parameter the
call’s own expected type fixes where no other argument does (f: (Int) -> Int = ident(fn x -> x + 1), g: Maybe<(Int) -> Int> = Some(fn x -> x * 3); §5
Type arguments from the arguments).
A parameter typed by a type parameter of the callee that nothing has solved
yet, and called in the body, is a function: the call solves it to a
function of its arguments’ types, returning what the call’s position needs.
Actor.start(workers, 0, fn s, f -> f(s)) makes the actor’s message type
(Int) -> Int, since the handler’s result is the state, an Int.
A result nothing fixes leaves the type argument undetermined
(§5 Determined type arguments).
In a list, vector or set literal, or a map literal’s keys or values, with no
expected type, the elements share one type, so a parameter annotated in one
element types the unannotated parameter at the same place in the others,
before or after it. A place is the lambda’s position inside the element,
through tuples, records and nested collection literals: in
[("a", fn d: Date -> f(d)), ("b", fn d -> g(d))] the second d is a
Date. An earlier element that is a function value rather than a lambda
(("a", month_name)) types the places of the elements after it. Elements
that annotate different types at one place are an element type mismatch.
Anywhere else no function type is expected, it is cannot infer type for parameter x, whose help says a later use does not type it. That covers an
unannotated binding (f = fn x -> x), a tuple element, a collection literal
whose elements type nothing at the parameter’s place, and the argument of a
generic constructor with no expected type (h = Some(fn x -> x)).
Type ascription
Section titled “Type ascription”value as Type checks value with Type as its expected type, exactly as
x: Type = value does, and is a Type. It gives a type where no
annotation can stand: a field of an anonymous struct literal, an argument,
a list element. An untagged literal takes the type its position gives it
(§18 Literals typed by their position), and so do an empty collection and
None:
import std::http.Route std::uuid.Uuid end once admin = { home: Route"GET /admin/{$}", user: `GET /admin/users/{id}` as Route<{id: Uuid}>, tags: [] as List<String>, } fn main() dbg admin.tags + ["new"] // ["new"] dbg None as Maybe<Int> // None end
as converts nothing (No Implicit Conversion). It admits what
assignability admits (§5 Assignability): a value as an interface it
implements, an embedded type as its enum, a collection under type-argument
conversion. Anything else is the annotation’s error at the value: with
x: Int, x as Float is type mismatch: expected Float, got Int, with
the help `as` doesn't convert a value; write `Int.to_float(x)`. The
help names the converting function for the scalar pairs a cast in another
language covers (Float.to_int, String.to_int, String.to_float,
Int.to_string and the like).
as binds like |> (§8 Operators and precedence). Two in a row,
a as T as U, are
`as` can't follow another `as`: an expression has one ascribed type.
An as whose value has the type without it changes nothing and is no
error. Where the value is a name, a field read or a number literal
(x as Int with x: Int), the language server marks the as
unnecessary.
No Implicit Conversion
Section titled “No Implicit Conversion”Taught in Scalars & Strings.
No value converts to another type implicitly. Int, Float and Decimal
are three types, and arithmetic needs one: x + y with an Int and a
Float is the error `+` needs two values of one type, and these are Int and Float. Conversions are
functions: Int.to_float(x) is total, and Float.to_int(y) is a
Maybe<Int> that truncates toward zero and is None for NaN and the
infinities (std::int, std::float).
Equality and Ordering Semantics
Section titled “Equality and Ordering Semantics”Taught in Interfaces & Dispatch.
Equality
Section titled “Equality”== compares values, never references. With no impl Equatable of its
own, a value compares structurally: a struct by every field, an enum by
variant and payload, a tuple by position, a collection by its elements (and
a map by entries).
struct User name: String age: Int end fn main() dbg User{name: "Ada", age: 36} == User{name: "Ada", age: 36} // True dbg [1, 2] == [1, 2] // True dbg Some(1) == None // False end
== on Float is reflexive: nan == nan is True, so pattern matching,
Maybe equality and container equality agree. This differs from IEEE 754 in
== only. == compares every bit otherwise, and
Float.equal_within(a, b, tolerance) compares within a tolerance.
Two Regex values are equal when their patterns are, and hash alike, at
the top or inside a collection, a tuple or a payload.
Two Dynamic values are equal when their contents are, as JSON values (an
object’s keys in any order, an Int never equal to a Float), and hash alike.
Two Type<T> witnesses are equal when they name the same type, and hash by
that type, so a witness can be a Set element or a Map key.
These have no equality: a function, an Iter, and a handle to running state
or to a resource outside the program. The handles are std’s Task, Sender,
Receiver, Arm, Context and Supervisor; std::io’s Reader, Writer
and File; std::fs’s FileSystem; std::process’s Child and Fake;
std::http’s Client, Exchange, Listener, Incoming, Mux, Jar and
Handle, and std::tls and std::net’s Certificate, TlsConfig, Conn and
TcpListener; std::csv’s Records and std::xml’s Tokens. A function’s
only identity is its closure, an Iter is a function over its source, and a
handle names something running or held outside the program. == or != on
one is a compile error:
`==` cannot compare `(Int) -> Int`: a function value has no equality;`==` cannot compare `Sender<Int>`: a handle to running state has no equality.
A value that holds one, in a field, a tuple or record part, an element or a
payload, has no equality either:
`==` cannot compare `Feed`: it holds `Iter<Int>`, and an Iter has no equality; collect it into a list with `Iter.to_list` to compare its elements.
A struct or enum with its own impl Equatable compares through it instead.
Equality bounds
Section titled “Equality bounds”A where T: Equatable bound means that T has equality: it accepts exactly
the types == accepts. A type with a hand-written or derived impl Equatable
meets it through that impl. A struct, enum or distinct type with no impl of
its own meets it by its structural equality, and == and Equatable.equal
on it in the body compare it as == does outside, through any nested type’s
own impl. A function, an Iter, a handle, and a value with no impl of its own
that holds one do not meet it ((Int) -> Int does not implement Equatable (required by `where T: Equatable`), and for a struct Op holding a
function, Op does not implement Equatable (required by `where T: Equatable`) with the help `Op` holds `(Int) -> Int`, and a function value has no equality).
struct Point x: Int y: Int end fn same<T>(a: T, b: T) -> Bool where T: Equatable a == b end fn main() p = Point{x: 1, y: 2} dbg same(p, Point{x: 1, y: 2}) // True dbg p in [p] // True dbg List.starts_with([p, p], [p]) // True end
So p in [q], List.contains, Iter.contains, List.starts_with and
the other std functions bounded by Equatable take Point with no
derive Equatable. A where T: Hashable bound follows the same rule
(Hashing and keys). Comparable does not: ordering needs a declared
impl (Ordering requires a declared Comparable).
Custom equality via impl Equatable
Section titled “Custom equality via impl Equatable”A hand-written impl Equatable replaces the structural comparison for its
type. It holds wherever the value sits: == on a container, a tuple, or a
struct or enum without its own Equatable compares each nested value of
that type through its impl, so [a] == [b], Some(a) == Some(b) and
Map.get({a => 1}, b) agree with a == b. Primitives compare directly.
Hashing and keys
Section titled “Hashing and keys”A Map finds its keys and a Set its elements by ==. So any value with
equality may be a key, at any depth: a tuple, a list, a struct, a distinct
value. A value with no equality may not: building a Set or Map over one
is an error at the expression that builds it
(`Iter<Int>` cannot be a Set element: an Iter has no equality or hashing; collect it into a list with `Iter.to_list` first).
Keys match by ==, so a NaN key is found again, and -0.0 and 0.0 are
one key. A key of a type with a hand-written impl Equatable matches
through it at any depth. The bucket comes from the type’s hand-written
impl Hashable when it has one; a type whose Equatable is hand-written and
whose Hashable is not hashes by its type alone, so all its keys share a
bucket. Every other value hashes structurally, as a derived Hashable does
(§12 Derive): a tuple mixes its slots in order, so
Hashable.hash((1, 2)) == 33, and an anonymous record its fields in name
order, so {b: 2, a: 1} hashes as (1, 2) does. Map equality and hashing
ignore order. An impl Hashable must give equal values equal hashes.
A key or element needs equality, not an impl: {p => 1}, Set[p],
Iter.to_set and Iter.group_by take a struct P with no Equatable or
Hashable of its own, as p == p does. A where T: Hashable bound accepts
what a key accepts: a type with an impl Hashable hashes through it, and any
other type with equality meets the bound and hashes in the body as its keys
do, so Hashable.hash(a) == Hashable.hash(b) whenever a == b. A derive
asks the same of each field: derive Hashable for W over a field of type
P, List<P> or (Int, P) is accepted, and over a P that holds a
function is no impl of `Hashable` for `P` (required via `derive Hashable for W`, field `f`) (§12 Derive).
Ordering requires a declared Comparable
Section titled “Ordering requires a declared Comparable”<, >, <= and >= call Comparable.compare, and a type has no
ordering unless it declares one. Structural equality has one meaning; a
structural order would depend on field order, so a reordering refactor would
change it silently. On a struct with no Comparable:
Point{x: 1, y: 2} < Point{x: 3, y: 4} // error: no impl of `Comparable` for `Point` (required via ordering operator `<`) // help: add `derive Comparable` to `Point` or write an `impl Comparable for Point` block
derive Comparable orders field by field (§12). The std types with a
natural order implement Comparable: Int, Float, Decimal, String,
Bool, Duration and the calendar types. List<T> and Vector<T> are
Comparable, lexicographically, when T is. Map and Set are not.
Comparable also gives every implementing type min, max and clamp,
open defaults written over compare: Int.min(a, b), Date.clamp(day, first..=last), Version.max(a, b) on a derived impl, or Comparable.min(a, b) in a function generic over T: Comparable. A tie returns the first
argument. clamp(value, range) holds value to a ClosedRange<T> (§3
Range literals): the range’s start when value is below it, its end when above,
and an unbounded Range.from(n) clamps only below. A backwards range
(10..=1) or an exclusive one (0..10) is an error when the program is
compiled, and a range computed when it runs goes through
ClosedRange.try_from. Float overrides all three: min and max are IEEE
754-2019’s minimum and maximum (NaN if either operand is NaN, and -0.0
below 0.0), and clamp keeps a NaN value NaN. A Float range with a NaN end
holds no value, so it is no ClosedRange, and no literal is NaN.
A tuple is Comparable when every element is: the first elements decide
unless they are Equal, then the second, and so on, and an element after
the deciding one is never compared. (1, "b") < (2, "a"). Ordering a
tuple with a non-Comparable element is a compile error naming the element
type. An anonymous struct is never Comparable, since nothing declares it:
no impl of `Comparable` for `{x: Int}` (required via ordering operator `<`); anonymous struct types cannot implement `Comparable` .
Its equality is unaffected.
NaN and the three comparison behaviours
Section titled “NaN and the three comparison behaviours”Float compares in three ways:
| Behaviour | On NaN | |
|---|---|---|
==, !=, Equatable.equal | reflexive | nan == nan is True |
Comparable.compare | a total order, NaN highest | Float.compare(nan, nan) is Equal |
<, <=, >, >= | IEEE 754 | nan <= nan is False |
== is reflexive so that a NaN key is found again in a Map, and
Hashable for Float treats every NaN, and both zeros, as one value.
compare agrees with ==, so a sort is deterministic and gathers NaNs at
one end. So a == b does not imply a <= b when both are NaN.