Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 57 ยท Defining types

Records, newtype and Type Synonyms

Learn Haskell record syntax and updates, field accessors, the difference between newtype, data and type, and when to use strict fields.

Algebraic data types give you the main tool for modelling data. This lesson looks at three closely related features that you will use in almost every program: records (constructors with named fields), type synonyms (type, a new name for an existing type) and newtype (a brand-new type with zero runtime cost).

Knowing which of data, newtype and type to choose is a daily decision in Haskell code. Real Haskell is read-only on this site. The runnable blocks are JavaScript stand-ins that show the ideas with objects and wrappers, and each says what it imitates.

Records in detail

Record syntax names the fields of a constructor:

HASKELL
data Employee = Employee
  { empName   :: String
  , empSalary :: Int
  , empTeam   :: String
  } deriving (Show, Eq)

Each field becomes an ordinary top-level function, so field names live in the module's namespace and must be unique within it. That is why they get prefixes such as emp. (The extension DuplicateRecordFields relaxes this, and OverloadedRecordDot allows e.empName syntax in recent GHC versions; both are covered in GHC Extensions Worth Knowing.)

Creating, reading and updating

HASKELL
ada :: Employee
ada = Employee { empName = "Ada", empSalary = 120, empTeam = "Core" }

empName ada                      -- "Ada"
ada { empSalary = 130 }          -- new Employee with a different salary
ada { empSalary = 130, empTeam = "Tools" }   -- several fields at once

The order of fields in a record construction does not matter, but you must supply every field, or GHC warns about missing fields (and reading a missing one fails at runtime). Update syntax always produces a new value; ada itself never changes.

Pattern matching on records

You can match on fields by name and ignore the rest:

HASKELL
raise :: Int -> Employee -> Employee
raise pct e@Employee { empSalary = s } =
  e { empSalary = s + s * pct `div` 100 }

isCore :: Employee -> Bool
isCore Employee { empTeam = t } = t == "Core"

With the RecordWildCards extension, Employee {..} brings all fields into scope as variables. It is convenient but can hide where names come from, so use it sparingly.

Show for records

Derived Show prints record syntax, so the output is valid Haskell:

HASKELL
Employee {empName = "Ada", empSalary = 120, empTeam = "Core"}
JS Records as immutable objects

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In Haskell you do not need freezing: there is no assignment at all, so a record can never change after it is built.

Type synonyms with type

type gives an alias for an existing type. The two names are completely interchangeable:

HASKELL
type Name = String
type Point = (Double, Double)
type Assoc k v = [(k, v)]

distance :: Point -> Point -> Double
distance (x1, y1) (x2, y2) = sqrt ((x2 - x1) ^ 2 + (y2 - y1) ^ 2)

String itself is a synonym: type String = [Char]. Synonyms improve readability and shorten long signatures, but they add no safety: a function that expects a Name will happily accept any String, and a Point is still just a pair.

HASKELL
type Meters = Double
type Seconds = Double

speed :: Meters -> Seconds -> Double
speed m s = m / s

speed 2 100    -- compiles, although the arguments are in the wrong order

If you need the compiler to tell the two apart, you need a real type: newtype.

newtype: a distinct type for free

HASKELL
newtype Meters  = Meters Double  deriving (Show, Eq, Ord)
newtype Seconds = Seconds Double deriving (Show, Eq, Ord)

speed :: Meters -> Seconds -> Double
speed (Meters m) (Seconds s) = m / s

Now speed (Seconds 2) (Meters 100) is a compile-time type error. A newtype has exactly one constructor with exactly one field, and at runtime the wrapper disappears: a Meters is represented just like a Double. You get type safety with no performance penalty.

Three ways to name a type

type Just another name. Same type.
newtype A new type, one field, no runtime cost.
data Any shape you like, with a small cost.
1 / 2

Records and newtype together

A newtype can use record syntax to get an unwrapping function for free. The convention is to call it runX or getX:

HASKELL
newtype Parser a = Parser { runParser :: String -> Maybe (a, String) }

newtype UserId = UserId { getUserId :: Int } deriving (Eq, Ord, Show)

getUserId :: UserId -> Int unwraps the value. Newtypes are also how you attach different type class instances to the same underlying type: the standard library has Sum Int and Product Int, two newtypes over Int that combine by addition and multiplication (more in Semigroups and Monoids).

newtype versus data

Why not use data Meters = Meters Double? There are two differences:

  1. Representation. A data value is a boxed constructor wrapped around its field. A newtype is erased by the compiler.
  2. Laziness. Matching a newtype constructor never forces anything, because the constructor does not exist at runtime. Matching Meters m on undefined is fine for a newtype but diverges for a data type with the same shape.

newtype must have exactly one field. If you need two, use data.

JS Wrapper types catch mix-ups

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Strict fields

By default, constructor fields are lazy: a field holds a thunk that may never be evaluated. A bang (!) before the field type makes it strict: the field is evaluated when the constructor is built.

HASKELL
data Account = Account
  { accId      :: !Int
  , accBalance :: !Double
  }

Strict fields prevent thunks from building up inside long-lived data such as counters and accumulators, which avoids space leaks. They also allow GHC to store small fields directly inside the constructor (with # UNPACK #). Use them for simple numeric fields; keep fields lazy when you rely on laziness, such as infinite lists or expensive optional computations. The topic continues in Strictness, Bang Patterns and seq.

Choosing between them

Situation Use
Shorter or clearer name for a complex type type
Keep two numbers or strings of different meaning apart newtype
Attach a different type class instance to an existing type newtype
Several fields or several alternatives data (maybe with records)
Long-lived numeric fields data with strict fields

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between type Name = String and newtype Name = Name String?

    A synonym is interchangeable with the original type. A newtype is a separate type that the compiler checks, yet it has no runtime wrapper.
  2. 2. How many fields and constructors may a newtype have?

    The compiler erases the wrapper, which only works if there is a single constructor holding a single field.
  3. 3. What does e { empSalary = 5 } do?

    Record update syntax builds a new record. The original value is immutable.
  4. 4. Why mark a numeric field strict with a bang?

    Strict fields are evaluated immediately, which prevents chains of delayed computations (space leaks).

Summary

  • Records name constructor fields, generate accessor functions, and support update syntax that returns a new value.
  • type creates an interchangeable alias; it improves readability but adds no safety.
  • newtype creates a distinct type with one constructor and one field, erased at runtime.
  • Use newtype to separate values with different meanings and to attach different type class instances.
  • Strict fields (!) evaluate on construction and help avoid space leaks.

Next: Maybe and Either.