TExcelTAD
Home › Haskell › Haskell Records

Haskell Records

When a constructor has several fields, remembering which Double is which gets hard: is it Employee "Ana" 4200 3 or Employee "Ana" 3 4200? Record syntax gives each field a name, and GHC generates a function to read each one.

haskell · try it yourself
data Employee = Employee
  { name :: String
  , salary :: Int
  , yearsAtCompany :: Int
  }
  deriving (Show, Eq)

main :: IO ()
main = do
  let ana = Employee {name = "Ana", salary = 4200, yearsAtCompany = 3}
      ben = Employee "Ben" 3900 1          -- positional construction still works
  print ana
  putStrLn (name ana)
  print (salary ben)
  print (map name [ana, ben])
Employee {name = "Ana", salary = 4200, yearsAtCompany = 3}
Ana
3900
["Ana","Ben"]

Every field name becomes an ordinary accessor function: name :: Employee -> String, salary :: Employee -> Int. That's why map name works. The derived Show instance prints the field names too.

Updating records

Values never change, so "updating" a record means making a copy with some fields replaced. The record update syntax value { field = newValue } does exactly that:

haskell · try it yourself
data Employee = Employee
  { name :: String
  , salary :: Int
  , yearsAtCompany :: Int
  }
  deriving Show

giveRaise :: Int -> Employee -> Employee
giveRaise percent e = e {salary = salary e + salary e * percent `div` 100}

celebrateAnniversary :: Employee -> Employee
celebrateAnniversary e = e {yearsAtCompany = yearsAtCompany e + 1}

main :: IO ()
main = do
  let ana = Employee {name = "Ana", salary = 4200, yearsAtCompany = 3}
      ana' = celebrateAnniversary (giveRaise 10 ana)
  print ana
  print ana'
Employee {name = "Ana", salary = 4200, yearsAtCompany = 3}
Employee {name = "Ana", salary = 4620, yearsAtCompany = 4}

The original ana is untouched. Naming the new version ana' (with a prime) is a Haskell habit for "a modified version of".

Pattern matching on records

You can match records positionally or by field name. Matching by name only mentions the fields you need:

haskell · try it yourself
data Book = Book
  { title :: String
  , author :: String
  , pages :: Int
  , available :: Bool
  }

shelfLabel :: Book -> String
shelfLabel Book {title = t, author = a} = t ++ " by " ++ a

status :: Book -> String
status Book {available = True} = "on the shelf"
status Book {available = False} = "on loan"

main :: IO ()
main = do
  let books =
        [ Book "Dune" "Frank Herbert" 412 True
        , Book "Kindred" "Octavia Butler" 264 False
        ]
  mapM_ (\b -> putStrLn (shelfLabel b ++ ": " ++ status b)) books
  print (sum (map pages books))
Dune by Frank Herbert: on the shelf
Kindred by Octavia Butler: on loan
676

Field puns and wildcards

Two GHC extensions shorten record code a lot. NamedFieldPuns lets you write Book {title} to bind a variable with the same name as the field; RecordWildCards lets Book {..} bind all fields at once:

haskell · try it yourself
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}

data Order = Order
  { orderId :: Int
  , customer :: String
  , quantity :: Int
  , unitPrice :: Double
  }

total :: Order -> Double
total Order {quantity, unitPrice} = fromIntegral quantity * unitPrice

summary :: Order -> String
summary o@Order {..} =
  "#" ++ show orderId ++ " " ++ customer ++ ": " ++ show quantity ++ " x " ++ show unitPrice ++ " = " ++ show (total o)

makeOrder :: Int -> String -> Order
makeOrder orderId customer = Order {..}   -- fields taken from variables in scope
  where
    quantity = 1
    unitPrice = 9.99

main :: IO ()
main = do
  putStrLn (summary (Order 1001 "Lin" 3 2.5))
  putStrLn (summary (makeOrder 1002 "Sam"))
#1001 Lin: 3 x 2.5 = 7.5
#1002 Sam: 1 x 9.99 = 9.99

Records with several constructors

Records can be combined with sum types, but be careful: an accessor for a field that only some constructors have will crash on the others.

haskell · try it yourself
data Account
  = Personal {owner :: String, balance :: Double}
  | Business {company :: String, balance :: Double, vatNumber :: String}
  deriving Show

label :: Account -> String
label (Personal o _) = o
label Business {company = c} = c ++ " (business)"

main :: IO ()
main = do
  let accounts = [Personal "Mia" 250, Business "Acme Ltd" 12000 "GB123"]
  mapM_ (putStrLn . label) accounts
  print (sum (map balance accounts))     -- safe: every constructor has balance
Mia
Acme Ltd (business)
12250.0

Here balance is safe because both constructors have it, but vatNumber (Personal "Mia" 250) would stop the program with "No match in record selector vatNumber". Prefer pattern matching for fields that only some constructors carry.

Tip: Field names are top-level functions, so two record types in the same module cannot both have a field called name (unless you enable DuplicateRecordFields). A common convention is to prefix fields with the type: employeeName, bookTitle.

Test yourself

Given data P = P { px :: Int, py :: Int } and p = P 1 2, what is p { py = 5 }?

  1. P 5 2
  2. P {px = 1, py = 5}
  3. It changes p in place
  4. A type error

What is the type of the accessor salary for data Employee = Employee { name :: String, salary :: Int }?

  1. Int
  2. Employee -> Int
  3. Int -> Employee
  4. String -> Int

What does RecordWildCards let you write?

  1. Order {..} to bind or fill all fields by name
  2. Records without types
  3. Fields that can be null
  4. Mutable records