Skip to content
Halyard
Project
Source code on Codeberg (opens in new tab)

Search

Menu

Types

Halyard has a strong, static type system with powerful type inference. This chapter covers built-in types and how to define your own.

Built-in Types

Primitive Types

TypeDescriptionExample
Int64-bit signed integer42, -7
Float64-bit floating point3.14, -0.5
DecimalArbitrary-precision decimal42d, 3.14d
BoolBoolean valueTrue, False
StringText string"hello"
CharSingle character'a', 'z'
SymbolInterned identifier:north, :ok
UnitEmpty value (like void)()
halyard
let x = 42

let pi = 3.14

let active = True

let name = "Alice"

let letter = 'A'

name

Halyard enforces strict type distinctions — Bool and Int are not interchangeable:

halyard
True + 1

Decimal Type

The Decimal type provides arbitrary-precision decimal arithmetic with up to 28 significant digits. Use it when exact decimal representation matters (e.g., financial calculations):

halyard
let price = 19.99d

let tax = 0.07d

let total = price + price * tax

total

Decimal literals use the d suffix: 42d, 3.14d, -0.001d. The arithmetic operators +, -, *, / and ^ and the comparison operators work with Decimal values; % does not, because it needs an Integral type (Int). See the Decimal stdlib module for additional functions like rounding, parsing, and conversion.

A Decimal never mixes with an Int or Float value. A number literal written beside a Decimal is built as a Decimal, exactly as written: price * 3 and price + 0.5 are Decimal arithmetic. An Int variable is not converted — use Decimal.fromInt:

halyard
-- A literal written beside a Decimal is built as a Decimal; an Int value
-- needs Decimal.fromInt.
import Decimal

let price = 19.99d

let quantity = 3

(price * 3, price * Decimal.fromInt quantity)
halyard
let price = 19.99d

let quantity = 3

price * quantity  -- an Int value never converts to Decimal

Symbol Type

Symbols are lightweight, interned identifiers prefixed with :. They're useful as tags, keys, and labels — anywhere you'd use a short string but want a distinct type:

halyard
[:north, :south, :east]

Symbols support equality (==, !=) and pattern matching, but not ordering (<, >, etc.):

halyard
[:north == :north, :north == :south]
halyard
let dir = :north

case dir of
    :north -> "going up"
    :south -> "going down"
    _ -> "going sideways"

For names with spaces or special characters, use quoted syntax:

halyard
:"hello world"

Compound Types

halyard
-- List of integers
let numbers =
    [1, 2, 3]
    -- Tuple

let pair = (42, "answer")

-- Optional integer
let maybe = Just 5

numbers

Tuples, lists, and records support equality (==, !=). Two tuples are equal if they have the same length and each element pair is equal. Two lists are equal if they have the same length and each element pair is equal. Two records are equal if they have the same field names in the same order and each value pair is equal.

Bracket List Syntax

List types can also be written with bracket syntax:

halyard
let numbers : [Int] = [1, 2, 3]

let names : [String] = ["Alice", "Bob"]

let nested : [[Int]] = [[1, 2], [3, 4]]

nested

Both List Int and [Int] are equivalent — use whichever reads better in context.

Parenthesized Types for Grouping

Use parentheses to group compound types as a single type argument:

halyard
let x : Result (Maybe Int) String = Ok (Just 5)

let y : Maybe [Int] = Just [1, 2, 3]

let z : [Maybe Int] =
    [ Just 1
    , Nothing
    , Just 2
    ]

z

Parentheses are needed when a type argument is itself a compound type (like Maybe Int). Without them, Result String Maybe Int would be ambiguous. Simple type names don't need parentheses:

halyard
let x : Result { name : String, age : Int } String = Ok { name = "Alice", age = 30 }

let y : Maybe { name : String, age : Int } = Just { name = "Bob", age = 25 }

let z : [{ name : String, age : Int }] = [{ name = "Alice", age = 30 }]

z

Newtypes

type Name = BaseType creates a nominally distinct type — values of Name and BaseType are not interchangeable, even though they have the same runtime representation.

Construct a newtype value with the type name as a constructor:

halyard
type UserId = Int

let id = UserId 42

case id of
    UserId n -> n

Extract the inner value with pattern matching:

case id of
    UserId n -> n

Generic newtypes are supported:

halyard
type Validated a = a

let score : Validated Int = Validated 99

case score of
    Validated n -> n

Two newtypes over the same base type are mutually incompatible:

halyard
-- UserId and PostId are distinct types — not interchangeable
type UserId = Int
type PostId = Int

fn greet : UserId -> String
fn greet x = "hello"

let pid = PostId 1

greet pid  -- Error: expected UserId, found PostId

The constructor and pattern match are identity at runtime — they exist only to satisfy the type checker. There is no performance cost.

Record newtypes

A newtype can wrap a record:

halyard
type Person = { name: String, age: Int }

let p = Person { name = "Alice", age = 30 }

case p of
    Person { name } -> name

Tuple newtypes

A newtype can wrap a tuple:

halyard
type Pair = (Int, String)

let p = Pair (1, "x")

case p of
    Pair (n, _) -> n

Type Aliases

type alias Name = Type creates a transparent synonym. The alias name and the underlying type are fully interchangeable at compile time — values flow between them without any constructor or pattern match. There is no runtime representation difference.

halyard
type alias UserId = Int

let id : UserId = 42
id + 1

Record aliases are the primary use case: give a long structural record type a short, reusable name.

halyard
type alias Person = { name : String, age : Int }

let p : Person = { name = "Alice", age = 30 }
p.age

A function accepting an open record type (one that uses .. to allow extra fields) accepts an aliased value that has additional fields beyond those required:

halyard
type alias Person = { name : String, age : Int }

fn greet : { name : String, .. } -> String
fn greet p = p.name

let alice : Person = { name = "Alice", age = 30 }
greet alice

Parameterized aliases

Aliases can take type parameters:

halyard
type alias Box a = { value : a }

let b : Box Int = { value = 42 }
b.value

Alias vs. newtype

An alias is transparent — a plain record satisfies PersonAlias and vice versa:

halyard
-- type alias: transparent — a plain record satisfies the annotation
type alias PersonAlias = { name : String, age : Int }

let a : PersonAlias = { name = "Alice", age = 30 }
a.name

A newtype (type Person = { name: String, age: Int }) is opaque — a plain record is not a Person. Use a newtype when you want the type checker to distinguish domain concepts; use an alias when you want a short name for a structural type without imposing any restriction.

Aliases in modules

type alias declarations inside a module are available in the module scope. Use type alias to name the module's public record shape so callers can annotate values without repeating the full structural type.

Nested aliases

An alias can reference another alias; the compiler expands them both before type-checking. There is no depth limit.

Newtypes vs single-variant enums

At runtime and in the type system, type UserId = Int and enum UserId = UserId Int are identical — both produce the same Enum value and support the same pattern matching. The distinction is intent:

  • Use type when you are naming a domain concept built on an existing type (UserId, Celsius, ValidatedEmail). The inner type is what matters; the name is the label.
  • Use enum when the variant name itself is meaningful, even with only one variant today — for example, because more variants are likely, or because the variant name represents a state or tag.
-- type: the Float is the value, Celsius is just the unit label
type Celsius = Float

-- enum: the variant name Loading is the value — no inner data matters
enum LoadingState = Loading | Loaded

Custom Types (Enums)

Define types with multiple variants using enum:

Simple Enums

halyard
enum Direction
    = North
    | South
    | East
    | West

let heading = Direction::North

heading

Multi-line format:

halyard
enum Direction
    = North
    | South
    | East
    | West

let heading = Direction::South

heading

Using Custom Types

halyard
enum Direction
    = North
    | South
    | East
    | West

let favorite : Direction = Direction::North

case favorite of
    Direction::North -> "Going up"
    Direction::South -> "Going down"
    Direction::East -> "Going right"
    Direction::West -> "Going left"

Variants with Data

Variants can carry data using parenthesized syntax:

halyard
enum Shape
    = Circle Float
    | Rectangle Float Float

fn area : Shape -> Float
fn area shape =
    case shape of
        Shape::Circle r -> 3.14159 * r * r
        Shape::Rectangle w h -> w * h

area Shape::Circle 5.0  -- 78.54
halyard
enum Shape
    = Circle Float
    | Rectangle Float Float

fn area : Shape -> Float
fn area shape =
    case shape of
        Shape::Circle r -> 3.14159 * r * r
        Shape::Rectangle w h -> w * h

area (Shape::Rectangle 4.0 3.0)  -- 12.0

Single-argument variants also support space-separated construction (Shape::Circle 5.0), while multi-arg requires parentheses:

halyard
enum Shape
    = Circle Float
    | Rectangle Float Float

Shape::Rectangle 10.0 20.0

Constructors Are Functions

A variant constructor is an ordinary function. enum Celsius = Celsius Int declares Celsius : Int -> Celsius, and enum Reading = Metric Int, String declares Metric : Int -> String -> Reading. Nothing special marks them out — they can be named, passed to a higher-order function, and partially applied like anything else:

halyard
import List

type Celsius = Celsius Int

-- A constructor IS a function, so it can be passed to a higher-order
-- function directly instead of being wrapped in a lambda.
List.map Celsius::Celsius [12, 19, 23]

Because they curry, supplying some arguments gives back a function awaiting the rest:

halyard
enum Reading = Metric Int String

-- Supplying some of a constructor's arguments gives back a function
-- awaiting the rest, exactly as with any other curried function.
let inCm = |n| Reading::Metric n "cm"

case inCm 3 of
    Reading::Metric n unit -> n

This is also why a constructor's arguments are type-checked exactly as a function call's are, including inside a lambda whose parameter has no annotation. let f = |x| Celsius::Celsius x constrains x to Int, so f "warm" is a compile error rather than a value carrying a String in an Int field.

Record-shaped variants — and so nominal record types, which are one — are the exception, following the same rule Rust uses for braced structs: they are constructed with the record syntax below rather than used as bare function values.

Variants with Record Data

halyard
enum User
    = Guest
    | Member { name : String, id : Int }

let user = User::Member { name = "Alice", id = 42 }

case user of
    User::Guest -> "Anonymous visitor"
    User::Member { name, id } -> "User " ++ name

Variants with Value Labels

ValueLabel is a built-in type — always available without imports, just like Bool, Maybe, or Result.

The ValueLabel type lets you embed integer-to-string mappings directly in enum variants. Each variant carries a (Int, String) pair — the integer code and its human-readable label:

halyard
-- Define an enum with ValueLabel data
-- Construct and match on ValueLabel variants
enum Gender
    = Male(ValueLabel 1 "Male")
    | Female(ValueLabel 2 "Female")
    | Other(ValueLabel 3 "Other")

case Gender::Male of
    Gender::Male _ -> "matched male"
    Gender::Female _ -> "matched female"
    Gender::Other _ -> "matched other"

When you construct a ValueLabel variant (e.g., Gender::Male), the integer and label are auto-supplied from the type definition — you never write Gender::Male (ValueLabel 1 "Male") manually.

This is useful for survey data, coded variables, and any domain where values have both numeric codes and descriptive labels. You can access individual label data with the ValueLabel module, or extract the full mapping as a ValueLabelSet at compile time:

halyard
-- Generate a ValueLabelSet from a ValueLabel enum
import ValueLabelSet

enum Gender
    = Male(ValueLabel 1 "Male")
    | Female(ValueLabel 2 "Female")
    | Other(ValueLabel 3 "Other")

let labels = ValueLabelSet.fromType Gender

ValueLabelSet.size labels

ValueLabelSet.fromType is a compiler intrinsic — it reads the mappings from the type definition at compile time. The compiler enforces that:

  • All variants must have exactly one ValueLabel field (no mixing with plain variants)
  • Integer values must be unique across variants

See Data Contracts for using ValueLabel enums with DataFrame validation, and ValueLabelSet for the full API.

Maybe Type

Represents optional values:

halyard
enum Maybe a = Just a | Nothing
  • Just a — contains a value
  • Nothing — no value
halyard
let present = Just 42

let absent = Nothing

case present of
    Just n -> "Got a value"
    Nothing -> "No value"

Result Type

Represents success or failure:

halyard
enum Result a e = Ok a | Err e
  • Ok a — success with value
  • Err e — failure with error
halyard
let success = Ok 42

case success of
    Ok value -> "Success"
    Err msg -> "Error: " ++ msg
halyard
let failure = Err "something went wrong"

case failure of
    Ok value -> "Success"
    Err msg -> "Error: " ++ msg

Generic Types

Types can have type parameters:

halyard
enum Pair a b = Pair(a, b)

let p = Pair::Pair (1, "hello")

p
halyard
enum Tree a
    = Leaf a
    | Node (Tree a) a (Tree a)

let tree : Tree Int =
    Tree::Node (Tree::Leaf 1) 2 (Tree::Node (Tree::Leaf 3) 4 (Tree::Leaf 5))

tree

Record Types

Common mistake: Writing enum Person = { name: String, age: Int } is an error — enum declares sum types with named variants. Use an inline record type annotation ({ name: String, age: Int }), a transparent alias (type alias Person = { name: String, age: Int }), or an opaque newtype (type Person = { name: String, age: Int }) instead. The alias keeps the plain record and the named type interchangeable; the newtype does not.

Define structured data with named fields:

halyard
let user : { id : Int, name : String, email : String, active : Bool } =
    { id = 1
    , name = "Alice"
    , email = "alice@example.com"
    , active = True
    }

user.name ++ " <" ++ user.email ++ ">"

Records support structural equality (==, !=). Two records are equal if they have the same field names in the same order and all field values are equal.

Open Record Types

Record types can use .. to allow extra fields beyond those specified:

halyard
let p : { name : String, age : Int, .. } =
    { name = "Alice"
    , age = 30
    , email = "a@b.com"
    }

p.name

Open record types are particularly useful with DataFrames for schema validation:

halyard
import DataFrame

-- Open record type allows extra fields

let data : DataFrame { name : String, age : Int, .. } =
    DataFrame.fromRecords
        [ { name = "Alice", age = 30, email = "alice@example.com" }
        ]

DataFrame.columns data

Use closed record types (no ..) when you want exact schema matches, and open record types when you need flexibility.

What an Open Record Promises

The .. in a function's signature is a promise about which fields the code may rely on, and it points in both directions.

A function that takes an open record may use only the fields its type lists. The fields behind the .. belong to the caller, who can pass any record with at least those fields, so the function cannot know they are there:

halyard
fn f : { x : Int | r } -> Int
fn f q = q.z

f { x = 1, z = 5 }

A function that returns an open record promises only the fields it lists. The record it builds may have more, and those extras are the function's own: the code that calls it can read id, and cannot read label even though makeItem put it there.

halyard
fn makeItem : Int -> { id : Int, .. }
fn makeItem n = { id = n, label = "item" }

let item = makeItem 1
item.id
halyard
fn makeItem : Int -> { id : Int, .. }
fn makeItem n = { id = n, label = "item" }

let item = makeItem 1
item.label

If you need the extra field, list it in the signature. A .. in a result is "at least these fields", and the fields you do not list stay out of reach so the function can change what it builds without breaking its callers.

A function-typed parameter swaps the two. Here ap hands its callback a record, so the callback may use only the fields ap's signature lists for it, and ap is free to hand it more:

halyard
fn ap : ({ x : Int, .. } -> Int) -> Int
fn ap cb = cb { x = 1 }

ap (|p| p.x)
halyard
fn ap : ({ x : Int, .. } -> Int) -> Int
fn ap cb = cb { x = 1 }

ap (|p| p.y)

To name a rest the caller chooses, give it a name ({ x : Int | r }): every place the signature writes r is the same set of fields, so a function can take a record and hand back the same record with its extras intact.

halyard
fn pass : { x : Int | r } -> { x : Int | r }
fn pass q = q

let w = pass { x = 1, z = 5 }
w.z

Symbol Field Names

When field names don't conform to Halyard's lowercase identifier syntax (e.g. uppercase or containing spaces), use symbol syntax in type annotations. This is most common with DataFrame schemas from external data sources (SPSS, Stata, Excel exports):

halyard
-- Symbol field names in type annotations let you reference columns
-- whose names don't conform to lowercase identifier syntax.
-- This is most useful for DataFrame schemas from external data sources:

import DataFrame

-- Uppercase column names (e.g. from SPSS/Stata exports). The annotation is
-- checked against the file at compile time, symbol names and all.
let df : DataFrame { :Name : String, :Age : Int, .. } = (DataFrame.readCsv "data/symbol_users.csv")?

-- Quoted field names for spaces or special characters
let df2 : DataFrame { :"Full Name" : String, :Score : Int, .. } = (DataFrame.readCsv "data/scores.csv")?

DataFrame.columns df2

Recursive Types

Types can reference themselves:

halyard
enum MyList a = Nil | Cons a (MyList a)

let nums =
    MyList::Cons 1 (MyList::Cons 2 (MyList::Cons 3 MyList::Nil))

nums

Type Inference

Halyard features automatic type inference, reducing the need for explicit annotations while maintaining type safety.

Let Bindings

Types are inferred from the assigned value:

halyard
let x = 42  -- Inferred as Int

let name = "Alice"  -- Inferred as String

let ratio = 3.14  -- Inferred as Float

let xs = [1, 2, 3]  -- Inferred as List Int

name

Add annotations when inference is ambiguous:

halyard
import List

let empty : [Int] = []  -- Needed: can't infer element type

List.length empty

Numeric Type Promotion

One rule governs Halyard's numbers: an Int widens to Float where a Float is needed; nothing else converts.

        Float
          ^
          |  widening: the Int value is converted to a real Float
         Int                 Decimal   <- isolated: no Int or Float value
                                          converts to or from it

When mixing Int and Float in arithmetic, the Int is promoted to Float:

halyard
let x = 1 + 2.5

let y = 3 * 1.5

x + y

An Int widens wherever a Float is expected — a declared parameter, a field, a return type or an annotation — whether it is a literal or a value:

halyard
-- An Int widens to Float wherever a Float is expected: a literal or a value,
-- converted to a real Float.
fn half : Float -> Float
fn half x = x / 2.0

let n = 3

(half 5, half n)

A Float never narrows to an Int; that is a compile error:

halyard
fn double : Int -> Int
fn double n = n * 2

double 2.5  -- a Float never narrows to Int

Where Int and Float values meet in one value — the elements of a list, the branches of an if or case — the result is Float, and each Int member is converted:

halyard
-- Where Int and Float values meet in one list or one `if`, the result is Float.
let xs = [1, 2.5, 4]

let y = if True then 1 else 2.5

(xs, y)

Only what is written at that place converts: an existing [Int] value is not a [Float] (convert one with List.map Math.toFloat), and a function Int -> b is not a Float -> b. Decimal is isolated — see Decimal Type: a literal beside a Decimal is a Decimal, an Int value needs Decimal.fromInt.

Pattern Type Propagation

Types are propagated to variables in destructuring patterns:

halyard
-- Tuple destructuring
let pair = (1, "hello")

let (x, y) = pair  -- x: Int, y: String

y
halyard
-- Case expression patterns
case (42, "test") of
    (x, y) -> y
halyard
-- Lambda parameter patterns with context
(1, 2) |> |(a, b)| a + b

Context-Based Lambda Inference

Lambda parameter types can be inferred from context when the expected type is known:

halyard
-- Pipe operator provides context
5 |> |x| x + 1
halyard
-- Higher-order function context
import List

-- Higher-order function context
[1, 2, 3] |> List.map (|x| x * 2)

-- x inferred as Int from list context

A lambda passed as an argument is typed after the call's other arguments, so its parameters take their types from them. Here x is a Float because prices is a [Float], and the literal 2 widens:

halyard
-- A lambda argument takes its parameter types from the call's other
-- arguments: `x` is a Float here, and the `2` widens.
import List

let prices = [1.5, 2.25]

List.map (|x| x * 2) prices

A lambda bound with let first has no call to take types from, so it is typed from its own body: let double = |x| x * 2 is Int -> Int, and double 2.5 is a type error.

halyard
-- A lambda bound with `let` is typed from its own body: `double` is Int -> Int.
let double = |x| x * 2

double 21

An annotation fixes a parameter's type explicitly:

halyard
(|x : Int| x + 1) 1

A letter in an annotation is not a placeholder to be filled in: it means "for all". let id = |x : a| x works at every type, so id 1 and id "s" are both fine. The value must keep that promise, so a body that needs more than "any a" is rejected; + needs a number:

halyard
-- A letter in an annotation means "for all": the lambda must work at every type
-- `a` could be, and `+` needs a number, which "every a" does not promise.
let inc = |x : a| x + 1

inc 2

Write the concrete type (|x : Int| x + 1) when the value only works at one.

Generic Function Results

Some functions return a generic type that can't be inferred from the arguments alone. In these cases, you must provide a type annotation on the let binding:

halyard
import Json

let data : Result { name : String } String = Json.parse "{\"name\": \"Alice\"}"

data

This applies to any function whose return type contains type variables that aren't determined by the input types (e.g., Json.parse : String -> Result a String — the a is unconstrained).

Best Practices

  1. Use newtypes for domain types — type UserId = Int prevents passing a PostId where a UserId is expected; the compiler catches the mistake
  2. Use type alias for structural reuse — when you have a long record type that appears in many annotations, type alias Row = { x: Int, y: String } gives it a short name without adding any type restriction
  3. Use enum for state machines and variants
  4. Keep types small — split large records into focused types
  5. Add type signatures to public functions
  6. Use Maybe for optional values instead of null
  7. Use Result for operations that can fail

Next Steps

Learn about pattern matching to work with your types.