Data types and pattern matching
A data declaration defines a type by listing every shape a value of that type
can have. The list is closed: nothing outside the declaration can add an
alternative, which is what lets the compiler check that a case handles all of
them.
data Shape = Circle Double | Rect Double Double
deriving (Show, Eq)
area :: Shape -> Double
area s = case s of
Circle r -> 3.141592653589793 * r * r
Rect w h -> w * h
main :: IO ()
main = putStrLn (show (area (Rect 2.0 3.0)))
6.0
Shape has two constructors. Circle takes one field, Rect two; a
constructor with fields is a function (Circle :: Double -> Shape), so
Circle 1.0 builds a value. Constructors are ordinary names: they are exported
from a module like anything else, and they can be passed to functions.
Parameterized and recursive types
A declaration may take type parameters, and a constructor may mention the type being declared:
data Tree a = Leaf | Node (Tree a) a (Tree a)
deriving (Show)
insert :: Ord a => a -> Tree a -> Tree a
insert x t = case t of
Leaf -> Node Leaf x Leaf
Node l v r
| x < v -> Node (insert x l) v r
| x > v -> Node l v (insert x r)
| otherwise -> t
toList :: Tree a -> [a]
toList t = case t of
Leaf -> []
Node l v r -> toList l ++ [v] ++ toList r
main :: IO ()
main = putStrLn (show (toList (insert 2 (insert 1 (insert 3 Leaf)))))
[1,2,3]
Leaf is a nullary constructor: it takes no fields, so it is a value rather
than a function.
newtype: a distinct type with no wrapper
newtype declares exactly one constructor with exactly one field. It is a
distinct type to the compiler, but construction and matching are the identity at
run time — no tag, no allocation beyond the field itself:
newtype Age = Age Int
deriving (Show)
birthday :: Age -> Age
birthday (Age n) = Age (n + 1)
main :: IO ()
main = putStrLn (show (birthday (Age 41)))
Age 42
Age is not Int: an Int will not type-check where an Age is expected, and
the compiler will not let you add two Age values unless you derive or write
the instance (deriving covers deriving newtype, which
borrows the representation’s instances).
An ordinary single-constructor data type stays tagged:
data Box = Box Int -- one constructor, but still a tagged value at run time
Records
A constructor can name its fields. The record form is still one constructor with positional fields; the names are for reading and writing them.
data Address = Address { city :: String, zip :: String }
data Person = Person { name :: String, age :: Int, address :: Address }
home :: Address
home = Address { city = "Berlin", zip = "10115" }
alice :: Person
alice = Person { name = "Alice", age = 30, address = home }
main :: IO ()
main = do
putStrLn alice.name
putStrLn alice.address.city
putStrLn (show alice.age)
Alice
Berlin
30
Three rules shape how records are used:
- Construction names every field.
Person { name = "Bob" }is an error; there is no partial construction and no default. - A pattern may name a subset. The fields left out are wildcards, so
Person { name = n }matches anyPersonand binds only the name. - A field is not a function.
alice.nameis projection; there is noname alice. Projection binds tighter than application, soshow alice.agemeansshow (alice.age).
Field names belong to the record, not to the module: two records may both
declare name, and the receiver’s type decides which one is meant.
Updating a record
value { field = newValue } copies the value with the named fields replaced.
Fields not named keep their current values, and updates nest:
older :: Person
older = alice { age = alice.age + 1 }
moved :: Person
moved = alice { address = alice.address { city = "Hamburg" } }
An update rebuilds one constructor, so it needs a record type with a single constructor. With two alternatives, which fields a value has is only known at run time, so the compiler refuses the update instead of failing later; match on the constructor and rebuild it instead.
Type synonyms
type gives an existing type another name. It introduces no new type and costs
nothing at run time:
type UserId = Int
type Handler = String -> String
Synonyms may take parameters (type Pair a = (a, a)) and are expanded by the
compiler wherever they appear.
Patterns
A pattern is how a value is taken apart. The same forms work in case
alternatives, in function clauses, in let/where bindings and in lambda
parameters (lambdas accept variables only — destructure in the body instead).
| Pattern | Matches |
|---|---|
x |
anything, binding it to x |
_ |
anything, binding nothing |
Circle r |
that constructor, binding its fields |
Person { name = n } |
a record, binding the fields named |
1, "abc", 'x' |
that literal |
[], x : xs |
the empty list, and a non-empty list head and tail |
(a, b) |
a pair (up to 64-tuples are in the library) |
x :| xs |
an infix constructor (see below) |
(f -> p) |
f applied to the value, when its result matches p (a view pattern) |
Patterns nest, and a function’s clauses are tried in order:
describe :: Maybe (Int, String) -> String
describe m = case m of
Nothing -> "nothing"
Just (0, _) -> "zero"
Just (n, label) -> label <> "=" <> show n
if is sugar for a two-alternative case on Bool; both branches are
required. Guards attach a condition to a clause and are tried in order:
classify :: Int -> String
classify n
| n < 0 = "negative"
| n == 0 = "zero"
| otherwise = "positive"
Guards also work on case alternatives:
sign :: Maybe Int -> String
sign m = case m of
Just n | n > 0 -> "positive"
| otherwise -> "non-positive"
Nothing -> "none"
View patterns
(expr -> pattern) applies expr to the value being matched and matches the
result. The expression is written in the scope around the pattern, so it can
read the enclosing parameters; the pattern binds the names of the result:
double :: Int -> Int
double n = n + n
zero :: Int -> Bool
zero (double -> 0) = True
zero _ = False
A result that does not match falls through to the next clause, so a view arm behaves like any other failed pattern:
classify :: Int -> Int
classify (double -> 0) = 10
classify (double -> n) = n
classify _ = 99
Views nest inside other patterns, and the expression is applied to the value
that position bound: in Just (double -> 0) it is applied to the Maybe’s
argument.
The checker does not reason about what a view’s expression returns, so an arm
whose pattern contains one counts as covering everything in the exhaustiveness
check (see below). A case the checker accepts can still fail at run time when
no view matches, so keep a catch-all clause after views that may fail.
Exhaustiveness
A case or a clause group must cover every constructor. This is a compile
error, not a run-time surprise:
data Color = Red | Green | Blue
name :: Color -> String
name c = case c of
Red -> "red"
Green -> "green"
Main.mog:4:10: type error: non-exhaustive case: missing patterns: Blue
4 | name c = case c of
| ^^^^^^
The message names the shapes that are missing. Extra alternatives are accepted
silently: a redundant arm is not reported, so keep case expressions to the
constructors that exist.
Advanced from here. Infix constructors, strictness and the list of absent forms are details you can skip on a first reading; the sections above are what everyday declarations need.
Infix constructors
A constructor whose name starts with : is written between its arguments.
Fixity is optional; without a declaration it is infixl 9, the same default as
an ordinary operator:
data NonEmpty a = a :| [a]
deriving (Show)
sumAll :: NonEmpty Int -> Int
sumAll (x :| xs) = x + sum xs
main :: IO ()
main = putStrLn (show (sumAll (1 :| [2, 3])))
6
infixr 5 :| would change how chains associate; :| itself is just a name, and
(:|) 1 [2] is the same value in prefix form.
Strictness
Fields are evaluated when the value is built. There are no thunks and no lazy fields: constructing a value with an expression that fails fails immediately, even if no field is ever read.
data P = P Int
main :: IO ()
main = do
let q = P (error "boom")
putStrLn "unreachable"
moggi: Uncaught exception base:Moggi.Exception.Type.ErrorCall:
boom
CallStack (from HasCallStack):
at Moggi.Err.error (libraries/base/src/Moggi/Err.mog:8:13)
at Main.main (Main.mog:4:8)
For the same reason there are no infinite or self-referential structures: a
value is finite, and recursion must consume what it produces
(Polymorphism covers inference; IO and effects
covers error in context).
GADTs
The where form of a data declaration states each constructor’s whole type
instead of a field list, so a constructor may say what its own parameters are:
data Expr a where
Lit :: Int -> Expr Int
Truth :: Expr Bool
render :: Expr Int -> String
render (Lit n) = show n
Lit is a constructor of Expr Int and of nothing else. Matching it is
something the checker uses: in an arm that matched Lit, the scrutinee’s index
is Int, so a function with signature Expr a -> a may return n there and
True in the Truth arm. This is refinement, and like Haskell’s it needs the
index to be rigid — a declared signature, or an instance head — because the
proof holds only inside the arm. A constructor whose result the scrutinee’s type
rule out (Truth at Expr Int) is inaccessible and is rejected, and a match
that misses a constructor the type admits is reported as non-exhaustive.
A variable the written result does not mention is existential:
data Box where
MkBox :: Show a => a -> Box
render (MkBox x) = show x
a is rigid inside the arm and cannot escape it — returning x is rejected.
The context is evidence the value carries, so show resolves through the
dictionary stored in the constructor; the dictionary is a field the source never
writes, and pattern matching binds it for you.
The same quantification may be written in an ordinary declaration:
data Box = forall a. Box a states the constructor’s variable with forall
instead of a where block, and the variable is existential either way. A
context may follow the quantifier (data Box = forall a. Show a => Box a), and
newtype accepts the form; both produce the constructor signature the where
form gives.
Other forms work as they do in an ordinary declaration: forall may be written
out (Anon :: forall b. b -> Box), a quantifier and a context may precede a
record block (MkBox :: forall a. Show a => { item :: a } -> Box a), newtype
accepts the same where form, and a signature may mention a higher-kinded
parameter.
Deriving follows the same rules as in Haskell. Eq, Show, Ord, Enum and
Bounded are derived from the constructors’ fields; Functor, Foldable and
Traversable are refused for a constructor that fixes its index (Lit :: Int ->
Expr Int is not a case of Expr a), and accepted when every constructor
returns the datatype at its parameters. Generic is not derived for a GADT.
At run time a GADT constructor is the ordinary tagged constructor: the index is not a field, and a context’s dictionary is the only field the source did not write.
What is not available
-
Type-level computation on indices. A GADT index is a type, not a value: there is no addition on
Nat, no type family, soPort (n + 1)cannot be written (Data kinds). -
As-patterns.
x@(Just n)is not supported; bind the whole value in the clause head and match again in the body, or use acaseon the bound name. -
Strictness annotations. There is no
!on fields and no~; evaluation is strict already.
Where next
- Polymorphism and inference — signatures, what the compiler infers, and when a binding is restricted to one type.
- Type classes — giving these types behaviour.
- Deriving —
Show,Eq,Ord,Functorand the rest, written by the compiler. - Kinds — the kind of
Shape,MaybeandTree.