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

Search

Menu

Code Examples

Explore Halyard through practical code examples. Click any example to open it in the playground.

507 examples

Basics

Collections

03b List Index Chain

collections
halyard
let grid = [[10, 20], [30, 40]]

grid[0][1]

Bracket List

collections
halyard
let xs : [Int] = [1, 2, 3]

let ys : [Int] = [4, 5, 6]

ys

Building Lists

collections
halyard
-- Prepend element
let list1 =
    1 :: [2, 3]
    -- Concatenate lists

let list2 = [1, 2] ++ [3, 4]
...

Dataframe Fromrecords

collections
halyard
import DataFrame

DataFrame.fromRecords
    [ { name = "Alice", score = 95 }
    , { name = "Bob", score = 87 }
    , { name = "Charlie", score = 92 }
...

Filter

collections
halyard
-- Filter: keep matching elements
import List

[1, 2, 3, 4] |> List.filter (|x| x > 2)

-- [3, 4]

Fold

collections
halyard
-- Fold: reduce to single value
import List

[1, 2, 3, 4] |> List.foldl (|acc x| acc + x) 0

-- 10

Length

collections
halyard
import List

fn length : [a] -> Int
fn length list =
    case list of
        [] -> 0
...

List Access

collections
halyard
let items = [10, 20, 30]

items[0]

List Ops

collections
halyard
-- Prepend (cons)
let consed =
    1 :: [2, 3]
    -- Concatenation

let joined = [1, 2] ++ [3, 4]
...

List Pattern

collections
halyard
let list = [1, 2, 3]

case list of
    [] -> "empty"
    [x] -> "single element"
    x :: xs -> "has multiple elements"

List Statistics

collections
halyard
-- List statistics: mean, median, variance, std, percentile, mode
import List
import Maybe

-- Integer list statistics
let scores = [60, 70, 80, 90, 100]
...

Lists

collections
halyard
let numbers = [1, 2, 3, 4, 5]

let names = ["Alice", "Bob", "Charlie"]

let empty : [Int] = []
...

Map

collections
halyard
-- Map: transform each element
import List exposing map

[1, 2, 3] |> map (|x| x * 2)  -- [2, 4, 6]

Multiline List

collections
halyard
let users =
    [ { name = "Alice", age = 30 }
    , { name = "Bob", age = 25 }
    , { name = "Charlie", age = 35 }
    ]
...

Multiline Record

collections
halyard
let config =
    { host = "localhost"
    , port = 8080
    , debug = True
    , maxConnections = 100
    }
...

Nested Record

collections
halyard
let data =
    { user = { profile = { name = "Alice" } }
    }

data.user.profile.name

Record Access

collections
halyard
let user = { name = "Alice", age = 30 }

user.name

Record Destructure

collections
halyard
let person = { name = "David", age = 40 }

let { name, age } = person

name

Record Multi Update

collections
halyard
let person = { name = "Alice", age = 30 }

let updated = { person | age = 31, name = "Alicia" }

updated.name

Record Pattern

collections
halyard
let person = { name = "Bob", age = 25 }

case person of
    { name, age } -> name

Record Rest

collections
halyard
let user =
    { name = "Carol"
    , age = 35
    , email = "carol@example.com"
    }
...

Record Update

collections
halyard
-- Record update syntax

let person = { name = "Alice", age = 30 }

let older = { person | age = 31 }
...

Record Workflow

collections
halyard
-- Record update creates a new record
let user = { name = "Eve", age = 28 }

let updatedUser = { user | age = user.age + 1 }

updatedUser.name

Records

collections
halyard
let user =
    { name = "Alice"
    , age = 30
    , email = "alice@example.com"
    }
...

Reverse

collections
halyard
import List

fn reverse : [a] -> [a]
fn reverse list =
    case list of
        [] -> []
...

Tuple Access

collections
halyard
let pair = (1, "hello")

let first = pair.0  -- 1

let second = pair.1  -- "hello"
...

Tuple Access 2

collections
halyard
let triple = (True, 42, "world")

triple.2

Tuple Destructure

collections
halyard
let (x, y) = (10, 20)

x + y

Tuple Pattern

collections
halyard
let pair = (3, 0)

case pair of
    (0, 0) -> "origin"
    (x, 0) -> "on x-axis"
    (0, y) -> "on y-axis"
...

Tuples

collections
halyard
let pair = (1, "one")

let triple = (True, 42, "hello")

let point = (3.5, 4.2)
...

Compliance

Control Flow

Case Enum

control-flow
halyard
enum Color = Red | Green | Blue

let color = Color::Green

let description =
    case color of
...

Catchall

control-flow
halyard
enum Color = Red | Green | Blue

let color = Color::Green

case color of
    Color::Red -> "primary"
...

Else If

control-flow
halyard
let score = 85

let grade =
    if score >= 90 then
        "A"
    else if score >= 80 then
...

Exhaustive

control-flow
halyard
enum Color = Red | Green | Blue

let color = Color::Blue

case color of
    Color::Red -> "red"
...

Guard Exhaustive

control-flow
halyard
let x = 0

case x of
    n if n > 0 -> "positive"
    n if n < 0 -> "negative"
    _ -> "zero"

Guards

control-flow
halyard
let number = -5

case number of
    n if n < 0 -> "negative"
    n if n == 0 -> "zero"
    n if n > 0 -> "positive"
...

If Expression

control-flow
halyard
let x = 5

let result =
    if x > 0 then
        "positive"
    else
...

If Multiline

control-flow
halyard
let condition = True

if condition then
    "yes"
else
    "no"

If Same Type

control-flow
halyard
let condition = True

-- Valid: both branches return Int
if condition then
    1
else
...

If Type Mismatch

control-flow
halyard
if False then
    1
else
    "zero"  -- Error: type mismatch

List Pattern

control-flow
halyard
let numbers = [1, 2, 3]

case numbers of
    [] -> "empty list"
    [x] -> "single element"
    [x, y] -> "two elements"
...

Maybe Handling

control-flow
halyard
let maybeUser = Just "Alice"

let displayName =
    case maybeUser of
        Just name -> name
        Nothing -> "Anonymous"
...

Maybe Type

control-flow
halyard
enum Maybe a = Just a | Nothing

Multiple Head

control-flow
halyard
let list = [1, 2, 3, 4]

case list of
    a :: b :: rest -> a + b
    x :: xs -> x
    [] -> 0

Nested Match

control-flow
halyard
let data = (3, 4)

case data of
    (a, b) -> a + b

Or Patterns

control-flow
halyard
enum Day
    = Monday
    | Tuesday
    | Wednesday
    | Thursday
    | Friday
...

Qualified Enum

control-flow
halyard
enum Color = Red | Green | Blue

let color = Color::Green

case color of
    Color::Red -> "fire"
...

Recursive Sum

control-flow
halyard
fn sum : [Int] -> Int
fn sum list =
    case list of
        [] -> 0
        x :: xs -> x + sum xs
...

Result Handling

control-flow
halyard
import String

let parseResult = Ok 42

case parseResult of
    Ok n -> "Parsed: " ++ String.fromInt n
...

Result Type

control-flow
halyard
enum Result a e = Ok a | Err e

Data Contracts

Display Mapped

data-contractsenumsdataframe
halyard
import DataFrame

enum Country
    = Germany
    | BurkinaFaso "Burkina Faso"
    | UnitedKingdom "United Kingdom"
...

Enum Column Torecords

data-contractsenumsdataframe
halyard
import DataFrame
import List
import Maybe
import Result
import ValueLabel
...

Geographic

data-contractsenumsdataframe
halyard
import DataFrame

enum Region
    = NorthEast "North East"
    | NorthWest "North West"
    | Midlands
...

Inline Value Labels

data-contractsenumsdataframe
halyard
import DataFrame

enum Education = Primary | Secondary | Tertiary | Postgraduate

let survey : DataFrame {
    respondent_id: Int,
...

Multiple Columns

data-contractsenumsdataframe
halyard
import DataFrame

enum City = Berlin | Munich | Hamburg
enum Gender = Male | Female | Other

let data : DataFrame { city: City, gender: Gender, .. } = (DataFrame.readCsv "data/demographics.csv")?
...

Non Exhaustive

data-contractsenumsdataframe
halyard
import DataFrame

enum YesNo = No | Yes

let data : DataFrame {
    response: [(0, YesNo::No), (1, YesNo::Yes), ..]
...

Open Closed Schema

data-contractsenumsdataframe
halyard
import DataFrame

enum Status = Active | Inactive | Pending

let exact : DataFrame { id: Int, name: String, status: Status } = (DataFrame.readCsv "data/users_status.csv")?
...

Stata Value Labels

data-contractsenumsdataframe
halyard
import DataFrame

enum Employment
    = Employed        (ValueLabel 1 "Employed")
    | Unemployed      (ValueLabel 2 "Unemployed")
    | NotInLaborForce (ValueLabel 3 "Not in Labor Force")
...

String Enum

data-contractsenumsdataframe
halyard
import DataFrame

enum City = Berlin | Munich | Hamburg

let data : DataFrame { name: String, city: City, .. } = (DataFrame.readCsv "data/users_cities.csv")?
...

Survey Use Case

data-contractsenumsdataframe
halyard
import DataFrame

enum AgeGroup
    = Under18 "Under 18"
    | Young "18-34"
    | Middle "35-54"
...

Value Label Shorthand

data-contractsenumsdataframe
halyard
import DataFrame

enum Education
    = Primary     (ValueLabel 1 "Primary")
    | Secondary   (ValueLabel 2 "Secondary")
    | Tertiary    (ValueLabel 3 "Tertiary")
...

Value Label Type

data-contractsenumsdataframe
halyard
import DataFrame
import ValueLabelSet

enum Education
    = Primary (ValueLabel 1 "Primary")
    | Secondary (ValueLabel 2 "Secondary")
...

Dataframe

Dataframe Corr

dataframestatisticscorrelation
halyard
import DataFrame

-- Pearson correlation matrix
let data =
    DataFrame.fromRecords
        [ { x = 1, y = 2 }
...

Dataframe Corr Spearman

dataframestatisticscorrelation
halyard
import DataFrame

-- Spearman rank correlation matrix (robust to outliers and non-linear monotone relationships)
let data =
    DataFrame.fromRecords
        [ { x = 1, y = 2 }
...

Dataframe Quantiles

dataframestatisticsquantile
halyard
import DataFrame

-- Multiple quantiles in one call
let data =
    DataFrame.fromRecords
        [ { score = 78 }
...

Dataframe Statistics

dataframestatisticsmean
halyard
import DataFrame

-- Column-wise descriptive statistics
let data =
    DataFrame.fromRecords
        [ { score = 78 }
...

Expr Aggregation

dataframeexpraggregation
halyard
-- Aggregation with DataFrame.Expr
import DataFrame

import DataFrame.Expr as Expr

DataFrame.fromRecords
...

Expr Arithmetic

dataframeexprarithmetic
halyard
-- Pipe-style arithmetic: Expr.mul for column * column
import DataFrame
import DataFrame.Expr exposing col
import Result

import DataFrame.Expr as Expr
...

Expr Basics

dataframeexprexpressions
halyard
-- DataFrame.Expr for composable column operations
import DataFrame
import DataFrame.Expr exposing col
import Result

import DataFrame.Expr as Expr
...

Expr Captured Var

dataframeexprvariable
halyard
-- Outer-scope variables are captured in expressions
import DataFrame
import Result

import DataFrame.Expr as Expr
...

Expr Case

dataframeexprconditional
halyard
-- Multi-branch conditional with Expr.cond
import DataFrame
import Result

import DataFrame.Expr as Expr
...

Expr Comparison

dataframeexprcomparison
halyard
-- Pipe-style comparison: Expr.gte for column >= literal
import DataFrame
import DataFrame.Expr exposing col
import Result

import DataFrame.Expr as Expr
...

Expr Concat

dataframeexprstring
halyard
import DataFrame
import Result

import DataFrame.Expr as Expr

let full = Expr.concatMany " " [@first, @last]
...

Expr Conditional

dataframeexprconditional
halyard
-- Conditional expressions with DataFrame.Expr
import DataFrame
import DataFrame.Expr exposing col, lit
import Result

import DataFrame.Expr as Expr
...

Expr Cumsum Extra

dataframewindowcumsum
halyard
import DataFrame

-- Running sum per region using window functions
DataFrame.fromRecords
    [ { region = "East", revenue = 100 }
    , { region = "East", revenue = 200 }
...

Expr Cumulative

dataframewindowcumsum
halyard
import DataFrame

-- Cumulative sum and mean per region using window functions
DataFrame.fromRecords
    [ { region = "East", revenue = 100 }
    , { region = "East", revenue = 200 }
...

Expr Date

dataframeexprstring
halyard
import DataFrame
import DataFrame.Expr exposing col, lit
import Result

import DataFrame.Expr as Expr
...

Expr Datetime

dataframeexprstring
halyard
import DataFrame
import DataFrame.Expr exposing col
import Result

import DataFrame.Expr as Expr
...

Expr Float Pred

dataframeexprnull
halyard
import DataFrame
import DataFrame.Expr exposing col
import Result

import DataFrame.Expr as Expr
...

Expr If Else

dataframeexprconditional
halyard
-- Simple if/else conditional with Expr.cond
import DataFrame
import Result

import DataFrame.Expr as Expr
...

Expr Import

dataframeexprimport
halyard
import DataFrame
import Result

import DataFrame.Expr as Expr

let source =
...

Expr In

dataframeexprcomparison
halyard
-- Membership test: Expr.in filters rows where the column value is in a list
import DataFrame
import Result

import DataFrame.Expr as Expr
...

Expr Infix Arithmetic

dataframeexprinfix
halyard
-- Infix arithmetic operators work directly on column references
import DataFrame
import Result

import DataFrame.Expr as Expr
...

Expr Infix Boolean

dataframeexprinfix
halyard
-- Boolean logic: && and || work with Expr values
import DataFrame
import Result

let df =
    DataFrame.fromRecords
...

Expr Infix Chained

dataframeexprinfix
halyard
-- Chained infix operations respect operator precedence
import DataFrame
import Result

import DataFrame.Expr as Expr
...

Expr Infix Comparison

dataframeexprinfix
halyard
-- Infix comparison operators produce boolean Expr for filtering
import DataFrame
import Result

let df =
    DataFrame.fromRecords
...

Expr Infix Scalar

dataframeexprinfix
halyard
-- Scalars are auto-coerced to Expr when used with infix operators
import DataFrame
import Result

import DataFrame.Expr as Expr
...

Expr Math

dataframeexprmath
halyard
-- Math functions: abs, log, ln, exp
import DataFrame
import Result

import DataFrame.Expr as Expr
...

Expr Mutate

dataframeexprapplyExprs
halyard
-- Add a computed column with applyExprs using tuple syntax
import DataFrame
import Result

import DataFrame.Expr as Expr
...

Expr Null

dataframeexprnull
halyard
-- Null handling: fillNull
import DataFrame
import DataFrame.Expr exposing col
import Result

import DataFrame.Expr as Expr
...

Expr Operators Overview

dataframeexproperators
halyard
-- Operators work directly on column references
import DataFrame
import Result

import DataFrame.Expr as Expr
...

Expr Quantile

dataframeexprquantile
halyard
import DataFrame

import DataFrame.Expr as Expr

-- Interquartile range components
let q1 =
...

Expr Regex String

dataframeexprstring
halyard
-- Extract year from date strings using regex capture
import DataFrame
import Result

import DataFrame.Expr as Expr
...

Expr Reuse

dataframeexprreuse
halyard
import DataFrame
import Result

import DataFrame.Expr as Expr

let revenue = @price * @qty
...

Expr Rolling

dataframewindowrolling
halyard
import DataFrame

-- Rolling window operations using partitionBy + withRollingSum/withRollingMean
DataFrame.fromRecords
    [ { region = "East", value = 1 }
    , { region = "East", value = 2 }
...

Expr Rolling Extra

dataframewindowrolling
halyard
import DataFrame

-- 7-day rolling average using window functions
DataFrame.fromRecords
    [ { dept = "East", sales = 10 }
    , { dept = "East", sales = 20 }
...

Expr Split

dataframeexprstring
halyard
import DataFrame
import DataFrame.Expr exposing col
import Result

import DataFrame.Expr as Expr
...

Expr String Extra

dataframeexprstring
halyard
import DataFrame
import Result

import DataFrame.Expr as Expr

-- Whitespace trimming (both sides)
...

Expr String Ops

dataframeexprstring
halyard
-- String operations with DataFrame.Expr
import DataFrame
import Result

import DataFrame.Expr as Expr
...

Expr String Transform

dataframeexprstring
halyard
-- String transformation chain
import DataFrame
import DataFrame.Expr exposing col
import Result

import DataFrame.Expr as Expr
...

Expr Symbol Col

dataframeexprsymbol
halyard
-- @name column references work directly with infix operators
import DataFrame
import Result

import DataFrame.Expr as Expr
...

Expr Type Cast

dataframeexprarithmetic
halyard
import DataFrame
import DataFrame.Expr exposing col
import Result

import DataFrame.Expr as Expr
...

Expr Window

dataframeexprwindow
halyard
import DataFrame
import Result

import DataFrame.Expr as Expr

let df =
...

Lineage Agg Origin

dataframelineageaggregation
halyard
import DataFrame
import DataFrame.Expr exposing col
import List

import DataFrame.Expr as Expr
...

Lineage Auto

dataframelineageprovenance
halyard
-- Lineage appears automatically when printing a DataFrame
import DataFrame
import DataFrame.Expr as Expr
import Result

let sales =
...

Lineage Byid

dataframelineageregistry
halyard
-- lineageById looks up a DataFrame in the lineage registry by its UUID
import DataFrame
import Maybe

let df =
    DataFrame.fromRecords
...

Lineage Byname

dataframelineageregistry
halyard
-- lineageByName searches the registry by name prefix, returns a list
import DataFrame
import List

-- lineageByName returns [Record] — empty list if no match
List.length (DataFrame.lineageByName "nonexistent-name")

Lineage Column

dataframelineage
halyard
-- DataFrame.columnLineage returns origin info for a column
import DataFrame

let df = DataFrame.fromRecords [{ name = "Alice", age = 30 }]

-- Returns Just { name, origin, transformations, dependencies }
...

Lineage Dag Join

dataframelineagedag
halyard
-- Join produces two parents in the DAG
import DataFrame
import List

let users =
    DataFrame.fromRecords
...

Lineage Full Record

dataframelineage
halyard
-- Full lineage record structure
import DataFrame
import DataFrame.Expr as Expr
import Result

let df =
...

Lineage Global Ops

dataframelineage
halyard
-- Global operations (filter, sort) are tracked separately
import DataFrame

let df =
    DataFrame.fromRecords
        [ { name = "Alice", age = 30 }
...

Lineage Join Origin

dataframelineagejoin
halyard
-- Joined columns track their source DataFrame
import DataFrame

let users =
    DataFrame.fromRecords
        [ { id = 1, name = "Alice" }
...

Lineage Parents Derived

dataframelineagedag
halyard
-- Derived DataFrames track parent operations
import DataFrame
import List
import Result

let df =
...

Lineage Parents Root

dataframelineagedag
halyard
-- Root DataFrames have no parents
import DataFrame

let df = DataFrame.fromRecords [{ name = "Alice", age = 30 }]

DataFrame.parents df

Lineage Rename Origin

dataframelineage
halyard
-- After rename, the transformation tracks the operation
import DataFrame
import Result

let df = DataFrame.fromRecords [{ name = "Alice", age = 30 }]
...

Lineage Sourcepath

dataframelineage
halyard
-- DataFrame.sourcePath returns Nothing for fromRecords
import DataFrame

let df =
    DataFrame.fromRecords
        [ { name = "Alice", age = 30 }
...

Lineage Tracking

dataframelineageprovenance
halyard
-- Track data transformation history
import DataFrame
import DataFrame.Expr as Expr
import Result

-- Create data and track transformations
...

Lineage Transformations

dataframelineage
halyard
-- Columns track their transformation history
import DataFrame
import Result

let df =
    DataFrame.fromRecords
...

Melt Reshape

dataframereshapemelt
halyard
-- melt reshapes wide data into long form by parsing column name prefixes
import DataFrame

-- Wide table: each measurement variable has one column per time point
let wide = DataFrame.fromRecords
    [ { nr = 1, var1_year1 = 10, var1_year2 = 20, var2_year1 = 5, var2_year2 = 8 }
...

Readcsv Columns

dataframereadCsvColumnsio
halyard
-- readCsvColumns reads only the specified columns from a CSV file
import DataFrame

case DataFrame.readCsvColumns [@name, @birth_date] "data/dates.csv" of
    Ok df -> DataFrame.columns df
    Err _ -> []

Recode

dataframerecodelabels
halyard
-- Remap values with automatic label transfer
import DataFrame

let df =
    DataFrame.fromRecords
        [ { id = 1, score = 1 }
...

Value Labels

dataframelabelsvalue-labels
halyard
-- Attach value labels for coded variables
import DataFrame
import ValueLabelSet

let gender = ValueLabelSet.fromList [(1, "Male"), (2, "Female")]
...

Variable Labels

dataframelabelsmetadata
halyard
-- Variable labels for column descriptions
import DataFrame

let df =
    DataFrame.fromRecords
        [ { id = 1, gender = 1 }
...

Window Functions

dataframeanalyticswindow-functions
halyard
-- SQL-style window functions
import DataFrame

-- Sample sales data with rank column
DataFrame.fromRecords
    [ { product = "Laptop", revenue = 1200, rank = 1 }
...

Withcolumns Batching

dataframeexprapplyExprs
halyard
-- applyExprs batches exprs so later ones can reference columns added earlier
import DataFrame
import Result

import DataFrame.Expr as Expr
...

Dataframe Type Safety

Date

Datetime

Decimal

Duration

Effects

Error Handling

Arg Type Map

error-handling
halyard
import List

List.map 42 [1, 2, 3]

-- Error: Type mismatch: expected a function (a -> b), found Int
...

Arg Type String

error-handling
halyard
import String

String.length 42

-- Error: Type mismatch: expected String, found Int
...

Block Align

error-handling
halyard
if True then
    0
  else         -- Error: 'else' must align with 'if'
    1

Block Missing Indent

error-handling
halyard
fn greet : String -> String
fn greet name =
"Hello, " ++ name   -- Error: body must be indented by at least 4 spaces

Block Nest

error-handling
halyard
let x =
x + 1          -- Error: the block must be indented by at least 4 spaces
               -- Hint: Indent the block to 4 spaces

Bool Correct

error-handling
halyard
let x = True

let y = False

x && y

Bool Error

error-handling
halyard
let x = true     -- Error: 'true' is not a Halyard keyword
                 -- Hint: Use `True` for boolean true

Bounds Error

error-handling
halyard
let items = [1, 2, 3]

items[10]  -- Error: Index 10 out of bounds for list of size 3

Bounds Safe

error-handling
halyard
let items = [1, 2, 3]

items[0]  -- 1

Branch Correct

error-handling
halyard
let x = 2

case x of
    1 -> "one"
    2 -> "two"
    _ -> "other"

Branch Mismatch

error-handling
halyard
let x = 2

case x of
    1 -> 42  -- Int
    2 -> "hello"  -- Error: Case branches have incompatible types: Int and String
    _ -> 0

Constructor Type

error-handling
halyard
case Just 5 of
    Ok n -> n  -- Error: Ok is a Result variant, and this case scrutinises a Maybe
    _ -> 0

Converting Types

error-handling
halyard
import Result

-- Maybe to Result (with error message)
let a = Just 5 |> Result.fromMaybe "was nothing"

-- Result to Maybe (discards error)
...

Correct Syntax

error-handling
halyard
fn double : Int -> Int
fn double x =
    x * 2

-- Pattern matching uses case...of
...

Else Align

error-handling
halyard
let x = 10
let result =
    if x > 5 then "big"
        else "small"   -- Error: else must align with if

Enum Case

error-handling
halyard
enum Direction = North | south    -- Error: Enum variant must start with uppercase

Fn Capture And Lambda

error-handling
halyard
let rate = 0.2

fn scaled : Float -> Float
fn scaled x = x * rate

let alsoScaled = |x| x * rate
...

Fn Missing Sig

error-handling
halyard
fn double x =        -- Error: missing type signature
    x * 2

Fuzzy Multiple

error-handling
halyard
import IO exposing print

let userName = "Alice"

let userAge = 30
...

Fuzzy Single

error-handling
halyard
import IO exposing print

let userName = "Alice"

let userAge = 30
...

Generic Annotation

error-handling
halyard
import Json

let data = Json.parse "{\"x\": 1}"

-- Error: Generic function result requires a type annotation for variable 'data'
...

Guard Correct

error-handling
halyard
let x = 5

case x of
    n if n > 0 -> "positive"
    n if n < 0 -> "negative"
    _ -> "zero"

Guard Type

error-handling
halyard
let x = 2

case x of
    n if n + 1 -> "bad"  -- Error: Guard expression must be Bool, found Int
    _ -> "ok"

Indent Error

error-handling
halyard
fn example : Int -> Int
fn example x =
let y = 1    -- Error: Function body must be indented by at least 4 spaces
    x + y

Js Record

error-handling
halyard
{ name: "Alice", age: 30 }
-- Error: JavaScript-style record syntax is not allowed
-- Hint: Use `=` instead of `:` for record field assignment
-- Example: `{ name = "Alice" }`

Json Fix

error-handling
halyard
import Json

let data : Result { x : Int } String = Json.parse "{\"x\": 1}"

data

Keywords

error-handling
halyard
return 5         -- Hint: Halyard is expression-based; the last expression is the return value
match x of       -- Hint: Use `case ... of` for pattern matching
function add     -- Hint: Use `fn` to define functions
var x = 5        -- Hint: Use `let` for variable bindings

Maybe Correct

error-handling
halyard
let present = Just 42

let absent = Nothing

case present of
    Just n -> "Got a value"
...

Maybe Module

error-handling
halyard
import Maybe

-- Transform present values
let mapped = Just 5 |> Maybe.map (|x| x * 2)

-- Chain operations that might return Nothing
...

Mismatched Delim

error-handling
halyard
let x = [1, 2)
-- Error: Mismatched delimiters — the `[` is closed by `)`

Module Fn Typo

error-handling
halyard
import List
List.fold [1, 2, 3] 0
-- Error: Function 'fold' is not declared in module 'List'. Did you mean 'foldl', 'foldr', or 'find'?

Null Error

error-handling
halyard
let x = null     -- Error: 'null' is not a Halyard keyword
                 -- Hint: Use `Nothing` for absent values

Pattern Type

error-handling
halyard
case 42 of
    "hello" -> 1  -- Error: Pattern type mismatch: expected Int, but pattern is String
    _ -> 0

Record Correct

error-handling
halyard
{ name = "Alice", age = 30 }

Result Module

error-handling
halyard
import Result

-- Transform success values
let mapped : Result Int String = Ok 5 |> Result.map (|x| x * 2)

-- Chain operations that might fail
...

Scope

error-handling
halyard
fn example : Int -> Int
fn example x =
    let inner = x + 1
    inner

inner  -- Error: Variable 'inner' is not in scope

Try Operator

error-handling
halyard
-- Unwrap Ok with ?, short-circuit on Err
let addOne = |x: Int| Ok (x + 1)
let result = 5 |> addOne
result?

Try Operator Err

error-handling
halyard
-- Inside a function that returns a Result, `?` on an Err returns that Err to the
-- caller (short-circuit): the rest of the function does not run.
fn mayFail : Int -> Result Int String
fn mayFail x = Err "something failed"

fn pipeline : Int -> Result Int String
...

Tuple Annotation

error-handling
halyard
let addPair = |(x, y): (Int, Int)| x + y
-- Error: Type annotations on tuple patterns must be on individual elements
-- Hint: Use `|(x: Int, y: Int)|` instead of `|(x, y): (Int, Int)|`.

Type Mismatch

error-handling
halyard
fn add : Int -> Int -> Int
fn add x y =
    x + y

add "hello" 5  -- Error: Expected Int but got String

Type Vs Alias

error-handling
halyard
enum Person = { name: String, age: Int }
-- Error: Expected enum variant, found record syntax
-- Hint: Use an inline record type annotation instead.

Unclosed Paren

error-handling
halyard
let x = (1 + 2
-- Error: Unclosed '(' — expected ')'

Undeclared

error-handling
halyard
let x = unknownVar    -- Error: Variable 'unknownVar' is not declared

Unexpected Delim

error-handling
halyard
let x = 1 + 2]
-- Error: Unexpected ']' — no matching '['

Variant Parens

error-handling
halyard
enum Outcome a e = Good a | Bad e

-- A variant's fields are juxtaposed, like a function's arguments: `Good a` declares
-- one field of type `a`. Parentheses GROUP, so `Good (a, e)` would declare one field
-- of TUPLE type instead -- a different type, written differently on purpose.
let result : Outcome Int String = Outcome::Good 5
...

Examples

Functions

A Lambda Captures

functions
halyard
let rate = 0.2

let scaled = |x| x * rate

scaled 10.0

A Let Is Positional

functions
halyard
let b = a + 1

let a = 1

b

Arity Overloading 1

functions
halyard
module CustomMath exposing ..

    fn add : Int -> Int
    fn add x =
        x + 1
...

Arity Overloading 2

functions
halyard
module CustomMath exposing ..

    fn add : Int -> Int
    fn add x =
        x + 1
...

Binder Named Like A Fn

functions
halyard
fn f : Int -> Int
fn f x = x * 10

fn viaParam : (Int -> Int) -> Int
fn viaParam f = f 2  -- the parameter f, not the function f
...

Common Filter

functions
halyard
import List

-- filter: keep matching elements
[1, 2, 3, 4] |> List.filter (|x| x > 2)

Common Fold

functions
halyard
import List

-- fold: reduce to single value
[1, 2, 3, 4] |> List.foldl (|acc x| acc + x) 0

Common Map

functions
halyard
import List

-- map: transform each element
[1, 2, 3] |> List.map (|x| x * 2)

Composition

functions
halyard
fn double : Int -> Int
fn double x =
    x * 2

fn addOne : Int -> Int
fn addOne x =
...

Currying

functions
halyard
fn add : Int -> Int -> Int
fn add x y =
    x + y

let add5 = add 5
...

Declarations Are Order Free

functions
halyard
fn isEven : Int -> Bool
fn isEven n = if n == 0 then True else isOdd (n - 1)

fn isOdd : Int -> Bool
fn isOdd n = if n == 0 then False else isEven (n - 1)
...

Defining

functions
halyard
fn greet : String -> String
fn greet name =
    "Hello, " ++ name ++ "!"

greet "Alice"  -- "Hello, Alice!"

Duplicate Sig

functions
halyard
fn add : Int -> Int
fn add x = x + 1

fn add : Int -> Int
fn add x = x + 2

Factorial

functions
halyard
module CustomMath exposing factorial

    fn factorial : Int -> Int
    fn factorial n =
        if n <= 1 then
            1
...

Factorial Case

functions
halyard
fn factorial : Int -> Int
fn factorial n =
    case n of
        0 -> 1
        1 -> 1
        _ -> n * factorial (n - 1)
...

Fibonacci

functions
halyard
module CustomMath exposing fibonacci

    fn fibonacci : Int -> Int
    fn fibonacci n =
        if n <= 1 then
            n
...

Fn Cannot Use Outer Value

functions
halyard
let rate = 0.2

fn scaled : Float -> Float
fn scaled x = x * rate

scaled 10.0

Fn Takes The Value As A Parameter

functions
halyard
fn scaled : Float -> Float -> Float
fn scaled rate x = x * rate

scaled 0.2 10.0

Generic Assign

functions
halyard
import List

let doubled = List.map (|x| x * 2) [1, 2, 3]

let result =
    [1, 2, 3, 4, 5]
...

Generic Compose

functions
halyard
fn compose : (b -> c) -> (a -> b) -> a -> c
fn compose g f x =
    g (f x)

let double = |x : Int| x * 2
...

Generic Identity

functions
halyard
fn identity : a -> a
fn identity x =
    x

identity 42

Higher Order

functions
halyard
-- Takes a function as argument
fn applyTwice : (Int -> Int) -> Int -> Int
fn applyTwice f x =
    f (f x)

applyTwice (|x : Int| x + 1) 5  -- 7

Higher Order Context

functions
halyard
module M exposing ..

    fn apply : (Int -> Int) -> Int -> Int
    fn apply f x =
        f x
...

Lambda As Pattern

functions
halyard
let withAlias = |x : Int as m| (x, m)

withAlias 42

Lambda Basics

functions
halyard
let addOne = |x : Int| x + 1

let addTwo = |x : Int y : Int| x + y

let addTuple = |(x : Int, y : Int)| x + y
...

Lambda Body Inferred

functions
halyard
-- When the body constrains the parameter type, the annotation is optional.
-- Here x must be Int because x + 1 requires Int.
let f = |x| x + 1

f 1

Lambda Generic Parameter

functions
halyard
let pair = |x| x  -- nothing constrains x: the identity function, at any type

(pair 1, pair "a")

Lambda Map

functions
halyard
import List

[1, 2, 3] |> List.map (|x| x * 2)

Lambda Multiline

functions
halyard
let compute =
    |x : Int|
        let y = 3
        x + y

compute 7

Lambda No Annotation

functions
halyard
|x| show x  -- only `show` constrains x, and nothing says which type it shows

Lambda Overloaded Parameter

functions
halyard
fn area : Float -> Float
fn area r = r * 3.0

fn area : Float -> Float -> Float
fn area w h = w * h
...

Lambda Record Fields

functions
halyard
let describe = |{ name: String, age: Int }| name

describe { name = "Alice", age = 30 }

Lambda Rest Pattern

functions
halyard
let getName = |{ name: String, .. }| name

getName { name = "Alice", age = 30 }

Lambda Tuple Add

functions
halyard
let addPair = |(x : Int, y : Int)| x + y

addPair (3, 4)

Lambda Typed

functions
halyard
let f1 = |x : Int| x + 1

let f2 = |x : Int y : Int| x + y

let f3 = |(x : Int, y : Int)| x + y
...

Lambda With Annotation

functions
halyard
let f = |x : Int| x + 1

f 1

Local Bindings

functions
halyard
import Math

fn quadraticFormula : Float -> Float -> Float -> (Float, Float)
fn quadraticFormula a b c =
    let discriminant = b * b - 4.0 * a * c
    let sqrtDisc =
...

Make Adder

functions
halyard
fn makeAdder : Int -> (Int -> Int)
fn makeAdder n =
    |x : Int| x + n

makeAdder 10 5

Native Pipes

functions
halyard
import List
import Math
import String

let a =
    "hello"
...

Nested Fn Shadowing

functions
halyard
fn helper : Int -> Int
fn helper x =
    x + 100

fn outer : Int -> Int
fn outer n =
...

Nested Fn Shadowing Profile

functions
halyard
fn helper : Bool -> String
fn helper b =
    "outerbool"

fn outer : Bool -> String
fn outer n =
...

Overloaded Call Every Argument

functions
halyard
fn d : Int -> Int -> Int
fn d a b = a + b

fn d : Float -> Float -> Float
fn d a b = a - b
...

Overloaded Hof

functions
halyard
module Apply exposing ..

    fn apply : (Int -> Int) -> Int -> Int
    fn apply f x =
        f x
...

Overloaded Value Ambiguous

functions
halyard
fn scale : Int -> Int
fn scale n = n * 10

fn scale : Float -> Float
fn scale x = x * 2.0
...

Overloaded Value Annotation

functions
halyard
fn scale : Int -> Int
fn scale n = n * 10

fn scale : Float -> Float
fn scale x = x * 2.0
...

Overloaded Value Composition

functions
halyard
fn scale : Int -> Int
fn scale n = n * 10

fn scale : Float -> Float
fn scale x = x * 2.0
...

Overloaded Value Hof

functions
halyard
fn scale : Int -> Int
fn scale n = n * 10

fn scale : Float -> Float
fn scale x = x * 2.0
...

Overloading Int

functions
halyard
module CustomMath exposing ..

    fn double : Int -> Int
    fn double x =
        x * 2
...

Overloading String

functions
halyard
module CustomMath exposing ..

    fn double : Int -> Int
    fn double x =
        x * 2
...

Overloading Toplevel

functions
halyard
fn inc : Int -> Int
fn inc x =
    x + 1

fn inc : Float -> Float
fn inc x =
...

Partial Call Ambiguous

functions
halyard
fn h : Int -> Int -> Int
fn h a b = a * b

fn h : Int -> Int -> Int -> Int
fn h a b c = a + b + c
...

Partial Call Annotated

functions
halyard
fn h : Int -> Int -> Int
fn h a b = a * b

fn h : Int -> Int -> Int -> Int
fn h a b c = a + b + c
...

Pattern Matching Fn

functions
halyard
fn length : [a] -> Int
fn length list =
    case list of
        [] -> 0
        x :: xs -> 1 + length xs
...

Pipe Chain

functions
halyard
fn double : Int -> Int
fn double x =
    x * 2

fn addOne : Int -> Int
fn addOne x =
...

Pipe Operator

functions
halyard
-- Pipe operator provides context from the left operand
5 |> |x| x + 1

Pipeline Example

functions
halyard
import List

[1, 2, 3, 4, 5]
    |> List.filter (|x| x > 2)
    |> List.map (|x| x * 2)

Record Field Pipe

functions
halyard
-- Mixed typed and untyped fields (untyped inferred from context)
{ x = 1, y = 2 } |> |{ x: Int, y }| x + y

Saturating Overload Wins

functions
halyard
fn d : Float -> Float
fn d x = x * 10.0

fn d : Int -> Int -> Int
fn d a b = a * b
...

Stdlib Chained Inference

functions
halyard
import List

-- Type inference flows through chained operations
-- Each lambda's parameter type is inferred from the previous result
[1, 2, 3, 4, 5]
    |> List.filter (|x| x > 2)
...

Stdlib Filter Inference

functions
halyard
import List

-- Lambda parameter type inferred from List.filter signature
List.filter (|x| x > 2) [1, 2, 3, 4, 5]

-- [3, 4, 5]

Stdlib Foldl Inference

functions
halyard
import List

-- Accumulator and element types inferred from List.foldl signature
-- foldl : (b -> a -> b) -> b -> List a -> b
-- With initial value 0 (Int) and List Int, acc : Int and x : Int
List.foldl (|acc x| acc + x) 0 [1, 2, 3, 4]
...

Stdlib Map Inference

functions
halyard
import List

-- Lambda parameter type inferred from List.map signature
List.map (|x| x * 2) [1, 2, 3]

-- [2, 4, 6]

Stdlib Zipwith Inference

functions
halyard
import List

-- Both parameters inferred from List.zipWith signature
-- zipWith : (a -> b -> c) -> List a -> List b -> List c
-- With List Int and List Int, both x : Int and y : Int
List.zipWith (|x y| x * y) [1, 2, 3] [4, 5, 6]
...

Tuple Arg Fst

functions
halyard
fn fst : (Int, String) -> Int
fn fst pair =
    case pair of
        (x, _) -> x

fst (42, "hello")

Tuple Arg Swap

functions
halyard
fn swap : (a, b) -> (b, a)
fn swap pair =
    case pair of
        (x, y) -> (y, x)

swap (1, "hello")

Type Signatures

functions
halyard
fn add : Int -> Int -> Int
fn add x y =
    x + y

add 3 4  -- 7

Getting Started

Http

Indentation

Basic Blocks

indentation
halyard
-- Function body must be indented
fn addOne : Int -> Int
fn addOne x =
    x + 1

addOne 5  -- 6

Case Indentation

indentation
halyard
-- Case branches must be indented from 'case'
let value = 2

let result =
    case value of
        1 -> "one"
...

Case Multiline Body

indentation
halyard
-- Case branch bodies can span multiple lines
let value = 2

let result =
    case value of
        1 ->
...

Continuation Argument

indentation
halyard
-- Multiline arguments work with COLLECTIONS (lists, records, tuples)

-- NOT with simple values like integers

import List
...

If Multiline

indentation
halyard
-- If-then-else with multiline expressions
let condition = True

let result =
    if condition then
        1 + 2
...

Let Block

indentation
halyard
-- Multiple let bindings at same indentation form a block
fn compute : Int -> Int
fn compute x =
    let a = x + 1
    let b = a * 2
    let c = b - 3
...

List Multiline

indentation
halyard
-- Lists can span multiple lines (Elm-style)
import List

let numbers = [1, 2, 3, 4, 5]

List.sum numbers
...

Local Fn Args

indentation
halyard
fn add : Int -> Int -> Int
fn add x y =
    x + y

let result = add 1 2
...

Multiline Function Call

indentation
halyard
-- Multi-line function calls work with collections on new lines
import List

-- Lambda on same line, list on indented new line
let doubled = List.map (|x| x * 2) [1, 2, 3]
...

Multiline Module Args

indentation
halyard
import List

List.map (|x| x * 2) [1, 2, 3]

Pipe Multiline

indentation
halyard
-- Pipes work naturally with multiline formatting
import List

let result =
    [1, 2, 3, 4, 5]
        |> List.map (|x| x * 2)
...

Record Multiline

indentation
halyard
-- Records can span multiple lines (Elm-style)
let person =
    { name = "Alice"
    , age = 30
    , city = "Paris"
    }
...

Same Column Pipe

indentation
halyard
-- An operator-led line continues the line above it at any column
import List

let result =
    [1, 2, 3, 4, 5]
    |> List.map (|x| x * 2)
...

Scope Nested

indentation
halyard
-- Indentation creates nested scopes within a block
fn example : Int -> Int
fn example x =
    let a = x + 1
    let b = a * 2
    let c = a + b
...

Scope Rules

indentation
halyard
fn example : Int -> Int
fn example n =
    let a = n + 1
    let b = a * 2
    let c = a + b
    c
...

Separate Expressions

indentation
halyard
-- Lines at the SAME indentation are separate expressions
let x = 1

let y = 2

let z = 3
...

Statement Boundary

indentation
halyard
-- A line break ends the statement unless the next line continues it
import List

let names = ["Ada", "Grace", "Alan"]

-- `names` is the whole argument: the list below is its own statement,
...

Landing

Aggregate

landingdataframeaggregation
halyard
import DataFrame
import DataFrame.Expr as Expr
import Result

let transactions : DataFrame { category : String, amount : Int, .. } =
    (DataFrame.readParquet "data/transactions.parquet")?
...

Column Safety

landingdata-contractscompile-time
halyard
import DataFrame

-- The annotation is the contract: halyard reads the file's schema while
-- compiling and checks these names and types against it.
let customers : DataFrame { customer_id : Int, name : String, lifetime_valu : Int, .. } =
    (DataFrame.readParquet "data/customers.parquet")?
...

Join Cardinality

landingdataframejoins
halyard
import DataFrame
import Result

let logins : DataFrame { name : String, day : String, .. } =
    (DataFrame.readCsv "data/logins.csv")?
...

Lineage

landinglineageprovenance
halyard
import DataFrame
import DataFrame.Expr exposing col
import List
import Maybe
import Result
...

Pipeline

landingtype-safetyschema-validation
halyard
import DataFrame
import DataFrame.Expr exposing col
import Result

-- `..` fixes the columns this pipeline needs and lets the file carry the rest.
let sales : DataFrame { transaction_id : Int, amount : Int, .. } =
...

Runtime Contract

landingdata-contractsruntime
halyard
import DataFrame
import Result

-- No annotation on this read, so nothing was checked while compiling.
-- checkSchema applies the same contract to data as it arrives.
type alias Inbound = { customer_id : Int, lifetime_value : Int, .. }
...

Lexical

Matrix

Modules

Access Add

modules
halyard
module CustomMath exposing add, multiply

    fn add : Int -> Int -> Int
    fn add x y =
        x + y
...

Access Multiply

modules
halyard
module CustomMath exposing multiply

    fn multiply : Int -> Int -> Int
    fn multiply x y =
        x * y
...

Comment In File Module

modules
halyard
module exposing celsiusToFahrenheit, fahrenheitToCelsius

-- Water freezes at 0 degrees Celsius, 32 Fahrenheit.

fn celsiusToFahrenheit : Float -> Float
fn celsiusToFahrenheit c = c * 1.8 + 32.0
...

Exposing

modules
halyard
-- Expose specific items
module exposing functionA, functionB, TypeA

-- Expose all
module exposing ..
...

Fibonacci

modules
halyard
module CustomMath exposing fibonacci

    fn fibonacci : Int -> Int
    fn fibonacci n =
        if n <= 1 then
            n
...

File Level

modules
halyard
module exposing createUser, getName

fn createUser : String -> Int -> { name: String, age: Int }
fn createUser name age = { name = name, age = age }

fn getName : { name: String, age: Int } -> String
...

File Level Indent Error

moduleserrors
halyard
-- A file-level module body must NOT be indented
module exposing fm

    fn fm : Int -> Int
    fn fm n = n + 1

Geometry Area

modules
halyard
import Math

module Geometry exposing Shape, area, perimeter

    enum Shape
        = Circle Float
...

Geometry Perimeter

modules
halyard
module Geometry exposing perimeter

    fn perimeter : Float -> Float
    fn perimeter r =
        2.0 * 3.14159 * r
...

Import Alias Exposing

modules
halyard
import List as L exposing length

length [1, 2]

Import Aliases

modulesimportsaliases
halyard
import List as L
-- Modules and import aliases
import Math as M

M.abs (L.length [1, 2, 3])

Import Exposing

modules
halyard
import List exposing map

-- Using built-in list functions directly
[1, 2, 3] |> map (|x| x * 2)  -- [2, 4, 6]

Import Exposing Bare

modules
halyard
import List exposing map, filter

map (|x : Int| x + 1) [1, 2, 3]

Indent Correct

modules
halyard
module CustomMath exposing add

    fn add : Int -> Int -> Int
    fn add x y =
        x + y
...

Indent Error

modules
halyard
-- Error: a NAMED module's body must be indented. The message is the parser's,
-- and it names the symptom (no member parsed) rather than the indentation.
module CustomMath exposing add

fn add x y = x + y    -- Wrong: not indented

Inline

modules
halyard
module CustomMath exposing add, multiply

    fn add : Int -> Int -> Int
    fn add x y =
        x + y
...

Math Module

modules
halyard
module exposing double, square

fn double : Int -> Int
fn double x = x * 2

fn square : Int -> Int
...

Module Body Declarations

modulestraitseffects
halyard
-- A module body holds effects, traits and impls, not only functions
module Shapes exposing area
    effect Audit
        note : String -> Unit

    trait Showy a
...

Recursive

modules
halyard
module CustomMath exposing factorial, fibonacci

    fn factorial : Int -> Int
    fn factorial n =
        if n <= 1 then
            1
...

Shadowing Math

modules
halyard
module Math exposing double

    fn double : Int -> Int
    fn double x =
        x * 2
...

Shapes Enum Module

modules
halyard
module Shapes exposing Shape, area

    enum Shape
        = Circle Float
        | Square Float
...

Stdlib Qualified

modules
halyard
import Json
import List
import Maybe
import Result
import String
...

Uses Stdlib

modules
halyard
module exposing greeting

import String

fn greeting : String -> String
fn greeting name =
...

Operators

Arithmetic

operators
halyard
let addition = 5 + 3

let subtraction = 10 - 4

let multiply = 6 * 7
...

Bitwise

operators
halyard
let n = 42

let inverted = ~n  -- -43 (two's-complement bitwise NOT)

let restored = ~inverted  -- 42 (double inversion is identity)
...

Comparison

operators
halyard
let eq = 5 == 5

let neq = 5 != 6

let lt = 3 < 5
...

Compose Backward

operators
halyard
-- Backward composition (g first, then f)
let addOne = |x : Int| x + 1

let double = |x : Int| x * 2

let doubleThenAdd = addOne << double
...

Compose Forward

operators
halyard
-- Forward composition (f first, then g)
let addOne = |x : Int| x + 1

let double = |x : Int| x * 2

let addThenDouble = addOne >> double
...

Division

operators
halyard
-- `/` requires Fractional (Float, Decimal — not Int); `//` requires
-- Integral (Int only). Mixing them up is a compile-time error.
let floatDiv = 10.0 / 3.0

let intDiv = 10 // 3
...

List Ops

operators
halyard
-- Cons (prepend element)
let consed1 = 1 :: [2, 3]

let consed2 : [Int] = 1 :: (2 :: [])

-- Concatenation
...

Logical

operators
halyard
-- And (both must be True)
let and1 = True && True

let and2 = True && False

-- Or (at least one must be True)
...

Pipe Forward

operators
halyard
fn double : Int -> Int
fn double x =
    x * 2

fn addOne : Int -> Int
fn addOne x =
...

Pipeline

operators
halyard
import List

-- Pipeline example
[1, 2, 3, 4, 5]
    |> List.filter (|x| x > 2)
    |> List.map (|x| x * 2)
...

Short Circuit

operators
halyard
-- False && ... returns False immediately without evaluating the right side
let result = False && True

result  -- False

String Concat

operators
halyard
"Hello, " ++ "World!"

Try Operator

operators
halyard
-- ? unwraps Ok values and short-circuits on Err
let addOne = |x: Int| Ok (x + 1)
let result = 5 |> addOne
result?

Type Promotion

operators
halyard
let x = 1 + 2.5

let y = 3 * 1.5

x + y

Pattern Matching

25b Guard Complete Partition

pattern-matching
halyard
let x = -3

-- A complete partition of Int — no catch-all needed.
-- The compiler verifies the guards cover every Int value.
case x of
    n if n > 0 -> "positive"
...

As Pattern

pattern-matching
halyard
let maybe = Just 42

case maybe of
    Just x -> (x, Just x)
    Nothing -> (0, Nothing)

As Pattern List

pattern-matching
halyard
let list = [1, 2, 3]

case list of
    x :: xs as all -> "Head"
    [] -> "empty"

Branch Mismatch

pattern-matching
halyard
case 1 of
    1 -> 42  -- Int
    2 -> "hello"  -- Error: Case branches have incompatible types
    _ -> 0

Cons

pattern-matching
halyard
let list = [1, 2, 3]

case list of
    x :: xs -> x  -- x is the head, xs is the tail
    [] -> 0  -- empty list case

Constructor

pattern-matching
halyard
let maybeValue = Just 42

case maybeValue of
    Just x -> "Got value"
    Nothing -> "Nothing"

Exhaustive

pattern-matching
halyard
enum TrafficLight = Red | Yellow | Green

let light = TrafficLight::Yellow

case light of
    TrafficLight::Red -> "stop"
...

Fn Nested

pattern-matching
halyard
fn addPairs : (Int, Int) -> (Int, Int) -> (Int, Int)
fn addPairs p1 p2 =
    case (p1, p2) of
        ((x1, y1), (x2, y2)) -> (x1 + x2, y1 + y2)

addPairs (1, 2) (3, 4)  -- (4, 6)

Fn Pattern

pattern-matching
halyard
fn fst : (a, b) -> a
fn fst pair =
    case pair of
        (x, _) -> x

fst
...

Guard Exhaustive

pattern-matching
halyard
let x = 0

case x of
    n if n > 0 -> "positive"
    n if n < 0 -> "negative"
    _ -> "zero"

Guard String Non Exhaustive

pattern-matching
halyard
let s = "hello"

-- All arms guarded, no catch-all: a guarded arm never counts as coverage,
-- so the matrix reports the gap even though no interval analysis applies to String.
case s of
    c if c == "hello" -> 1
...

Guards

pattern-matching
halyard
let number = 42

case number of
    n if n < 0 -> "negative"
    n if n == 0 -> "zero"
    n if n < 10 -> "small positive"
...

Lambda Record

pattern-matching
halyard
-- Record destructuring
let describe = |{ name: String, age: Int }| name

describe { name = "Bob", age = 25 }

Lambda Tuple

pattern-matching
halyard
-- Tuple destructuring
let addPair = |(x : Int, y : Int)| x + y

addPair (3, 4)  -- 7

Let Record

pattern-matching
halyard
let user = { name = "Alice", age = 30 }

let { name, age } = user

name

Let Tuple

pattern-matching
halyard
let point = (10, 20)

let (x, y) = point

x + y

List Exact

pattern-matching
halyard
let list = [1, 2]

case list of
    [] -> "empty"
    [x] -> "single"
    [x, y] -> "pair"
...

Literal

pattern-matching
halyard
let x = 1

case x of
    0 -> "zero"
    1 -> "one"
    _ -> "many"

Multi Cons

pattern-matching
halyard
let list = [1, 2, 3, 4]

case list of
    a :: b :: rest -> a + b
    x :: xs -> x
    [] -> 0

Nested

pattern-matching
halyard
import String

let result = Ok Just 5

case result of
    Ok (Just x) -> "Success with value: " ++ String.fromInt x
...

Or Binding

pattern-matching
halyard
let point = (5, 2)

case point of
    (x, 1) | (x, 2) | (x, 3) -> x  -- x is bound in all alternatives
    _ -> 0

Or Pattern

pattern-matching
halyard
enum Direction
    = North
    | South
    | East
    | West
...

Qualified Enum

pattern-matching
halyard
enum Color = Red | Green | Blue

let color = Color::Green

case color of
    Color::Red -> "fire"
...

Record

pattern-matching
halyard
let person = { name = "Alice", age = 30 }

case person of
    { name, age } -> name

Record Rest

pattern-matching
halyard
let user =
    { name = "Bob"
    , age = 25
    , email = "bob@example.com"
    }
...

Recursive

pattern-matching
halyard
fn sum : [Int] -> Int
fn sum numbers =
    case numbers of
        [] -> 0
        x :: xs -> x + sum xs
...

Tuple

pattern-matching
halyard
let pair = (3, 0)

case pair of
    (0, 0) -> "origin"
    (x, 0) -> "on x-axis"
    (0, y) -> "on y-axis"
...

Tuple Non Exhaustive

pattern-matching
halyard
let p = (1, "x")

-- Tuple columns are checked too: only (0, _) is covered.
case p of
    (0, _) -> 1

Type Mismatch

pattern-matching
halyard
case 42 of
    "hello" -> 1  -- Error: Pattern type mismatch: expected Int, but pattern is String
    _ -> 0

Type Unify

pattern-matching
halyard
let x = 2

case x of
    1 -> 42  -- Int
    2 -> 3.14  -- Float: the branches join at Float
    _ -> 0

Unreachable

pattern-matching
halyard
let x = False

case x of
    _ -> "anything"  -- This matches everything
    True -> "true"  -- Warning: Unreachable pattern

Variable

pattern-matching
halyard
let point = (3, 4)

case point of
    (x, y) -> x + y

Variant Patterns

pattern-matchingenums
halyard
enum Shape = Circle Float | Rect { width : Float, height : Float }

let s = Shape::Rect { width = 2.0, height = 2.5 }

case s of
    Circle r               -> r
...

Wildcard

pattern-matching
halyard
let tuple = (42, "ignored")

case tuple of
    (x, _) -> x  -- Ignore second element

Process

Runtime Errors

Table

Time

Traits

A Binding Shadows A Trait Method

traits
halyard
-- A `let` binds, even when the file derives the trait whose method it is named
-- for: `eq` here is the Bool it looks like. The same holds for a nested `fn`, a
-- parameter, a lambda parameter and a `case` binder. Only a `fn` DECLARATION is
-- reserved — a top-level one always, a `module` member only where the name is
-- called bare somewhere that could reach it, which example 11 shows. (A task
-- `expecting` field is the
...

A Qualified Module Member Is Not Reserved

traits
halyard
-- A module member's only use form is `M.show`, which is a different name from the
-- bare `show` a derived impl claims — so deriving `Show` here reserves nothing and
-- the member keeps compiling. A bare `show` ANYWHERE IN THIS FILE would reserve
-- it, because there the bare name is the one dispatch takes: the unit is the file,
-- not the `module` block, so a bare use in a top-level function beside the block
-- counts too.
...

Constrained

traitsconstraints
halyard
trait Show a
    show : a -> String

trait Show for Int
    fn show x = "n"
...

Derived Method Name Is Taken

traits
halyard
-- The derived type's OWN shape: `deriving (Show)` injects `trait Show for Colour`,
-- and a top-level `fn show` at that very type is rejected at its declaration.
-- Before this rule the program compiled and died at run time instead, with
-- `expected String or Symbol, found Enum(...)`.
enum Colour = Red | Green deriving (Show)
...

No Clause Means No Reservation

traits
halyard
-- Control: with no trait and no deriving clause anywhere, the same `fn show`
-- is an ordinary function and runs.
fn show : Int -> String
fn show n = "mine"

show 1

Own Numeric Trait

traitsnumericconstraints
halyard
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
...

Polymorphic Recursion

traitsconstraintserrors
halyard
trait Show a
    show : a -> String

trait Show for Int
    fn show x = "n"
...

Polymorphic Recursion Rewrite

traitsconstraints
halyard
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]
...

Reserved Name At An Unrelated Type

traits
halyard
-- The collision is by NAME: `fn show` at an unrelated type (Int -> String, not
-- the derived Show's profile) is still rejected.
enum Colour = Red | Green deriving (Show)

fn show : Int -> String
fn show n = "mine"
...

Sealed Numeric

traitsnumericerrors
halyard
type Score = Score Int
trait Numeric for Score

Show

traitsdispatch
halyard
trait Show a
    show : a -> String

trait Show for Int
    fn show x = "an int"
...

Sort

traitsordlist
halyard
import List

[3, 1, 2] |> List.sort

Types

03b Record Newtype

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

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

case p of
    Person { name } -> name

03c Tuple Newtype

types
halyard
type Pair = (Int, String)

let p = Pair (1, "x")

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

Alias Resolved

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

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

Annotation Letter Is For All

typesgenericserrors
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

Bool Int Error

types
halyard
True + 1

Bracket List All

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

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

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

Callback Parameter Lists What It Receives

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

ap (|p| p.x)

Callback Reads Past What It Receives

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

ap (|p| p.y)

Case Pattern

types
halyard
-- Case expression patterns
case (42, "test") of
    (x, y) -> y

Compound

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

let pair = (42, "answer")
...

Constructor As Function

types
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.
...

Constructor Partial Application

types
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"
...

Decimal Int Value Error

typesnumericdecimal
halyard
let price = 19.99d

let quantity = 3

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

Decimal Literals

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

let price = 19.99d
...

Decimal Type

types
halyard
let price = 19.99d

let tax = 0.07d

let total = price + price * tax
...

Float Never Narrows

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

double 2.5  -- a Float never narrows to Int

Generic Pair

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

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

p

Generic Tree

types
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))
...

Hof Context

types
halyard
-- Higher-order function context
import List

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

Inference

types
halyard
let x = 42  -- Inferred as Int

let name = "Alice"  -- Inferred as String

let ratio = 3.14  -- Inferred as Float
...

Inference Annotation

types
halyard
import List

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

List.length empty

Int Widens To Float

typesnumeric
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
...

Json Parse Annotation

types
halyard
import Json

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

data

Lambda Annotation

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

Lambda From Arguments

typeslambdainference
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]
...

Lambda Pattern

types
halyard
-- Lambda parameter patterns with context
(1, 2) |> |(a, b)| a + b

Let Lambda Own Body

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

double 21

Maybe Type

types
halyard
enum Maybe a = Just a | Nothing

Maybe Usage

types
halyard
let present = Just 42

let absent = Nothing

case present of
    Just n -> "Got a value"
...

Multiline Enum

types
halyard
enum Direction
    = North
    | South
    | East
    | West
...

Named Rest Keeps The Extras

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

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

Numeric Join

typesnumeric
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)

Numeric Promotion

types
halyard
let x = 1 + 2.5

let y = 3 * 1.5

x + y

Open Record Alias

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

Open Record Dataframe

types
halyard
import DataFrame

-- Open record type allows extra fields

let data : DataFrame { name : String, age : Int, .. } =
    DataFrame.fromRecords
...

Open Record Parameter Reads Only Its Fields

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

f { x = 1, z = 5 }

Open Record Result Hides The Rest

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

let item = makeItem 1
item.label

Open Record Result Lists What It Promises

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

let item = makeItem 1
item.id

Parameterized Alias

types
halyard
type Validated a = a

let score : Validated Int = Validated 99

case score of
    Validated n -> n

Parenthesized All

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

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

let z : [Maybe Int] =
    [ Just 1
...

Pipe Context

types
halyard
-- Pipe operator provides context
5 |> |x| x + 1

Primitives

types
halyard
let x = 42

let pi = 3.14

let active = True
...

Record Type

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

Recursive

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

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

nums

Result Err

types
halyard
let failure = Err "something went wrong"

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

Result Ok

types
halyard
let success = Ok 42

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

Result Type

types
halyard
enum Result a e = Ok a | Err e

Shape Construction

types
halyard
enum Shape
    = Circle Float
    | Rectangle Float Float

Shape::Rectangle 10.0 20.0

Simple Enum

types
halyard
enum Direction
    = North
    | South
    | East
    | West
...

Symbol Basic

typessymbol
halyard
[:north, :south, :east]

Symbol Equality

typessymbolequality
halyard
[:north == :north, :north == :south]

Symbol Field Names

typesrecordsdataframe
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
...

Symbol Pattern

typessymbolpattern-matching
halyard
let dir = :north

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

Symbol Quoted

typessymbol
halyard
:"hello world"

Tuple Destructure

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

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

y

Type Alias

types
halyard
type UserId = Int

let id = UserId 42

case id of
    UserId n -> n

Type Alias All

types
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 }]
...

Type Alias Fn Arg

type-aliastypesfunctions
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 }
...

Type Alias Parameterized

type-aliastypesgenerics
halyard
type alias Box a = { value : a }

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

Type Alias Record

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

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

Type Alias Scalar

type-aliastypes
halyard
type alias UserId = Int

let id : UserId = 42
id + 1

Type Alias Vs Newtype

type-aliasnewtypetypes
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

Using Enum

types
halyard
enum Direction
    = North
    | South
    | East
    | West
...

Value Label Enum

typesenumvalue-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")
...

Value Label Fromtype

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

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

Variant Data Circle

types
halyard
enum Shape
    = Circle Float
    | Rectangle Float Float

fn area : Shape -> Float
fn area shape =
...

Variant Data Rect

types
halyard
enum Shape
    = Circle Float
    | Rectangle Float Float

fn area : Shape -> Float
fn area shape =
...

Variant Record

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

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

Valuelabel

Valuelabelset

Variables