On this page
Traits
A trait describes behaviour that many types can share. It is Halyard's mechanism
for ad-hoc polymorphism: one name (show, compare, …) that resolves to a
different implementation depending on the type it is used with. Traits replace the
old catch-all comparable type variable with something precise and extensible.
Why traits exist
Before traits, a function that needed to compare or order its argument relied on a
magic comparable type variable. That worked for the built-in primitives but you
could never extend it: there was no way to say "my type can be ordered too", and
the compiler could not tell you when a type genuinely lacked an ordering. Traits fix
both problems — ordering and equality are now ordinary, nameable capabilities, and
the compiler reports a clear error when a required implementation is missing.
Declaring a trait
A trait declaration names the capability, a type parameter, and the method signatures that any implementation must provide:
trait Show a
show : a -> String
This says: a type a implements Show when it provides a show function of type
a -> String.
Implementing a trait
trait … for … gives an implementation of a trait for a concrete type. Each method
is written as an ordinary fn (the signature is taken from the trait definition, so
none is repeated here):
trait Show a
show : a -> String
trait Show for Int
fn show x = "an int"
trait Show for Bool
fn show x = "a bool"
(show 42, show True)
Compiled
show 42 dispatches to the Show for Int implementation and show True to the
Show for Bool one — the compiler picks the right one from the argument's type.
Only one implementation of a trait may exist per type. A second
trait Show for Int block is a compile error (DuplicateTraitImpl), and an
implementation of a trait that was never declared is a TraitNotFound error.
Constrained functions
A function can require that its type parameter implement a trait by writing a
constraint before its signature with =>:
trait Show a
show : a -> String
trait Show for Int
fn show x = "n"
fn describe : Show a => a -> String
fn describe x = show x
describe 7
Compiled
fn describe : Show a => a -> String reads "for any a that implements Show,
describe takes an a and returns a String." Inside the body, show x resolves
through the constraint. Calling describe with a type that has no Show
implementation is a MissingTraitImpl error, reported at the call site.
Multiple constraints are written in parentheses:
fn pair : (Show a, Show b) => a -> b -> String
A constrained function cannot call itself at a larger type
A function with a constraint is compiled once for each type it is used at: describe 1
and describe 2.5 each run the describe written for their own type. So a constrained
function must not call itself -- directly, or through another constrained function that
calls it back -- at a type that contains its own type variable:
fn layers : Show a => Int -> a -> String
fn layers n x = if n == 0 then show x else show x ++ layers (n - 1) [x]
layers at Int calls layers at List Int, which calls it at List (List Int), and
so on: it would need a version for every one of those types. Halyard rejects the call where
the type grows, with PolymorphicRecursion ("layers is used inside its own recursion
at [a], a larger type than its own"), even when the recursion would stop at run time
(layers 0 1), because the versions are made before the program runs. Rust rejects the
same program for the same reason.
trait Show a
show : a -> String
trait Show for Int
fn show x = "n"
trait Show for List a
fn show xs = "list"
fn layers : Show a => Int -> a -> String
fn layers n x = if n == 0 then show x else show x ++ layers (n - 1) [x]
layers 0 1
Compiled
A recursive call at the function's own type (layers (n - 1) x), at a fixed type
(layers (n - 1) 1), or at its type variables in another order is fine. So is any
recursion that does not go through a constraint: fn depth : Int -> a -> Int may call
depth (n - 1) [x], because it is compiled once.
To write such a function, pass the operation in instead of requiring it through the constraint, so the function itself has no constraint:
fn layers : (a -> String) -> Int -> a -> String
fn layers f n x =
if n == 0 then f x
else f x ++ layers (|xs| "[" ++ List.foldl (|acc y| acc ++ f y) "" xs ++ "]") (n - 1) [x]
layers (|i| "n") 2 7 is "n[n][[n]]". Or call it at a concrete type when you know
the depth.
import List
fn layers : (a -> String) -> Int -> a -> String
fn layers f n x =
if n == 0 then f x
else f x ++ layers (|xs| "[" ++ List.foldl (|acc y| acc ++ f y) "" xs ++ "]") (n - 1) [x]
layers (|i| "n") 2 7
Compiled
Superconstraints
A trait can require another trait with needs. Ord (ordering) needs Eq
(equality), because anything you can order you can also compare for equality:
trait Ord a needs Eq a
compare : a -> a -> Int
When you implement Ord for a type, the compiler also checks that Eq is
implemented for it — a missing superconstraint surfaces as MissingTraitImpl.
Built-in traits: Eq, Ord, and Hash
Halyard ships built-in Eq and Ord implementations for every primitive type:
Int, Float, Decimal, String, Bool, and Char. This is what makes ==
and ordering work out of the box, and it is what List.sort relies on:
import List
[3, 1, 2] |> List.sort
Compiled
List.sort has the signature Ord a => [a] -> [a], so sorting a list of a type
without an Ord implementation is a compile error rather than a silent runtime
surprise. List.minimum, List.maximum, and Math.min / max / clamp are
constrained by Ord in the same way; List.unique is constrained by Eq.
Because Ord needs Eq, a value with an Ord implementation can always be
compared with == as well.
Hash
Hash a requires Eq a and provides:
hash : Hash a => a -> Int
All primitive types (Int, Float, Decimal, String, Bool, Char,
Symbol) have built-in Hash implementations when deriving (Hash) appears
anywhere in the program. The function uses FNV-1a (64-bit) and returns a signed
Int. Equal values always produce the same hash:
enum Color = Red | Green | Blue deriving (Hash)
hash Color::Red -- some deterministic Int
hash Color::Red == hash Color::Red -- True
hash Color::Red == hash Color::Blue -- False (in practice)
Hash is the foundation for future dictionary and set types where the key type
must be hashable.
Built-in numeric traits
Halyard's numeric type hierarchy is expressed as a trait tower. Each level is a superconstraint of the one below:
Numeric a — Int, Float, Decimal (+, -, *, ^)
└── Integral a — Int only (//, %)
└── Fractional a — Float, Decimal (/)
└── Real a — Float, Decimal (transcendental functions)
The numeric traits are closed
Numeric, Integral, Fractional and Real are implemented by the built-in number
types only, exactly as the tower above lists them. They have no methods you could write:
+, -, *, /, the comparisons and number literals are the runtime's own operations
on Int, Float and Decimal, and a function constrained by Numeric a builds its
literals and runs its arithmetic for whichever of those types it is called at. So an
implementation for a type of your own is rejected where you write it:
type Score = Score Int
trait Numeric for Score
is SealedTraitImpl ("Trait Numeric cannot be implemented for type Score: only the
built-in numeric types implement it"). To compute with a Score, take the number out
(case s of Score n -> n) and compute with the Int, or declare a trait of your own --
it may require Numeric, as in trait Scaled a needs Numeric a -- and implement that
for the built-in types you need:
trait Scaled a needs Numeric a
unit : a -> a
trait Scaled for Int
fn unit x = x
trait Scaled for Float
fn unit x = x
fn h : Scaled a => a -> a
fn h x = unit x + 1
(h 2, h 2.5) is (3, 3.5). Such a trait's instances are built-in number types only:
using one at another type is a MissingTraitImpl for Numeric there.
type Score = Score Int
trait Numeric for Score
Compiled
trait Scaled a needs Numeric a
unit : a -> a
trait Scaled for Int
fn unit x = x
trait Scaled for Float
fn unit x = x
fn h : Scaled a => a -> a
fn h x = unit x + 1
(h 2, h 2.5)
Compiled
+, -, *, and ^ accept any Numeric type. The other arithmetic
operators are narrower:
/requiresFractional—FloatandDecimal, but notInt. Dividing twoIntvalues is a compile-time error; convert withMath.toFloatfirst.//and%requireIntegral—Intonly, neitherFloatnorDecimal. Passing aFloatorDecimaloperand to//or%is a compile-time error; useMath.truncate/Math.floorfor float truncation instead.
This means 1 / 2 does not compile: the ambiguity between fractional
division (1.0 / 2.0) and integer division (1 // 2) must be resolved
explicitly, rather than silently defaulting to a Float result.
The Real constraint is required by the six transcendental Math functions:
| Function | Signature |
|---|---|
Math.sqrt | Real a => a -> Maybe a |
Math.pow | Real a => a -> a -> Maybe a |
Math.exp | Real a => a -> Maybe a |
Math.log | Real a => a -> Maybe a |
Math.log10 | Real a => a -> Maybe a |
Math.log2 | Real a => a -> Maybe a |
These accept both Float and Decimal arguments. Passing Int, String, or
Bool is a compile-time MissingTraitImpl error.
Real also provides two conversion methods:
Real.toRational : a -> Decimal— converts aFloatorDecimaltoDecimal. ForFloatinputs the conversion is exact for values representable withinDecimal's 28-digit precision; larger or non-representable values round.Real.fromInt : Int -> a— produces aFloatorDecimalfrom an integer literal. The return type must be determinable from context; a bareReal.fromInt 5without an annotation is anAmbiguousTypeerror.
The two methods are reached through import Real:
import Math
import Maybe
import Real
-- Float dispatch
Math.sqrt 4.0 -- Just 2.0 : Maybe Float
-- Decimal dispatch (full decimal arithmetic, no float round-trip)
Math.sqrt 4.0d -- Just 2.0d : Maybe Decimal
-- fromInt with annotation
let x : Decimal = Real.fromInt 5 -- 5d
To turn an Int value into a Decimal without a trait, use Decimal.fromInt: an Int
value never converts to Decimal by itself (see the types guide's
Decimal Type).
deriving — automatic implementations
For common structural traits, Halyard can generate an implementation automatically.
Write deriving (TraitName) at the end of an enum definition:
enum Direction = North | South | East | West deriving (Eq, Ord, Show, Hash)
Supported derivable traits:
| Trait | Effect |
|---|---|
Eq | eq tests constructor identity (and field equality for tuple variants) |
Ord | compare orders constructors by declaration order, then fields |
Show | show renders to a string like "North" or "Pair 1 2" |
Hash | hash computes a deterministic integer via FNV-1a and polynomial field mixing |
Deriving Ord automatically includes Eq. Deriving Hash automatically includes
Eq. Attempting to derive an unknown trait name is a compile error
(DerivingUnknownTrait).
A deriving clause reserves the trait's method names for a top-level fn.
Writing deriving (Show) — or a written trait Show for T impl — makes a
top-level fn show a compile error at any type and any arity, naming the trait
and where the impl came from, reported at your declaration. A clause in a
module body or in a module file is a trigger too; one nested inside a block is
not. Which units it reaches is stated once, with the run and import cases, in
Functions → "Trait method names are reserved".
A binding of that name is a different thing: it shadows the method, and the
reference means the binding. That holds for a let, a nested fn, a parameter, a
lambda parameter and a case binder — so let show = 5
beside deriving (Show) is fine and is the Int. A task expecting field is the
exception, and it is a bug: a field named like a derived method is displaced by
the method and the program fails at run time — or, if the same file declares a
module member of that name, is rejected with the error pointing at the member.
Rename the field. The full rule, including which
module members are reserved and why the unit is the file, lives in one place:
Functions → "Trait method names are reserved".
Sorting and comparing derived-Ord enums
List.sort, List.maximum, List.minimum, and List.unique all work on
user-defined enums that deriving (Ord):
enum Priority = Low | Medium | High deriving (Ord, Eq)
let tasks = [High, Low, Medium]
List.sort tasks
-- [Low, Medium, High]
Constructors are ordered by their declaration order — the first constructor
written is the smallest. In the example above, Low sorts before Medium
because it appears first in the enum Priority = ... declaration, regardless
of the constructor names themselves.
This declaration-order contract currently applies to enums where every
constructor is nullary (no fields, like Low | Medium | High). Enums with
tuple or record constructors still derive a working compare function for
direct use (compare, <, >, etc.), but List.sort and friends do not yet
dispatch on them at runtime.
Row constraints: Lacks
A row constraint is a condition on the open row variable of a DataFrame type,
separate from the trait system. The only row constraint today is Lacks.
r Lacks "col" asserts that the row variable r does not already contain a column
named col. It is written in the same constraint prefix as trait constraints:
fn addTimestamp : r Lacks "ts" => DataFrame { | r } -> DataFrame { ts: DateTime | r }
fn addTimestamp df = ...
When the function is called, the compiler checks that the concrete row bound to r
does not include ts. If it does, a LacksConstraintViolated compile error is
emitted:
-- ERROR: r Lacks "ts" violated — input already has column "ts"
addTimestamp alreadyHasTsDf
Multiple Lacks constraints use the parenthesised form:
fn addAuditCols
: (r Lacks "created_at", r Lacks "updated_at")
=> DataFrame { | r }
-> DataFrame { created_at: DateTime, updated_at: DateTime | r }
fn addAuditCols df = ...
Lacks and trait constraints may appear together in the same prefix:
fn process : (Show a, r Lacks "result") => a -> DataFrame { | r } -> DataFrame { result: String | r }
When the open row variable r is not yet bound (the DataFrame is still abstract),
the constraint is deferred — no error fires until a concrete row is substituted.
When r is bound to RowTail::Unknown (a DataFrame whose schema is not statically
known, such as the result of fromRecords), the constraint is vacuously satisfied:
halyard's gradual typing accepts unknown schemas where concrete ones would be checked.
Lacks constraints enable safe composition of schema-extending pipelines:
fn withId : r Lacks "id" => DataFrame { | r } -> DataFrame { id: Int | r }
fn withTimestamp : r Lacks "ts" => DataFrame { | r } -> DataFrame { ts: DateTime | r }
-- OK: withId adds "id", then withTimestamp adds "ts" — no overlap
let result = df |> withId |> withTimestamp
Without Lacks, calling withTimestamp on a DataFrame that already has a ts
column would silently produce a broken schema. With Lacks, it is a compile error.
What traits do not support yet
Halyard's traits are deliberately a small, well-understood core. The following are not supported today:
- Associated types — a trait has one type parameter and method signatures only.
- Multi-parameter traits — a trait constrains exactly one type variable.
- Polymorphic recursion — a constrained function calling itself at a larger type
(
f [x]insidef) is rejected; see A constrained function cannot call itself at a larger type. - Implementing the numeric traits for your own types —
Numeric,Integral,FractionalandRealare closed; see The numeric traits are closed.
These are natural future extensions, but leaving them out keeps dispatch simple and every trait error precise.