typestar

Records in Haskell

Record syntax names each field, defines an accessor per field, and copies a value with changes.

-- a record names each field and defines an accessor function for it
data Roast = Roast
  { roastName :: String, originCity :: String, bagsOnHand :: Int }
  deriving (Show)

-- build one by naming fields, in whatever order suits you
house :: Roast
house = Roast { roastName = "House", originCity = "Antigua",
                bagsOnHand = 9 }

-- an accessor is an ordinary function from the record to one field
label :: Roast -> String
label r = roastName r ++ " (" ++ originCity r ++ ")"

-- update syntax copies the record, replacing only the listed field
sell :: Int -> Roast -> Roast
sell n r = r { bagsOnHand = bagsOnHand r - n }

main :: IO ()
main = putStrLn (label house) >> print (sell 4 house)

How it works

  1. data Roast = Roast declares three fields, so a name like bagsOnHand becomes a function from a Roast to that one field.
  2. house is built by naming fields, which is why their order inside the braces is free.
  3. sell n r = r { bagsOnHand = bagsOnHand r - n } returns a copy with one field replaced, leaving house untouched.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
683
Tokens
107
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 92 seconds.

Type this snippet

Step 2 of 3 in Types & records, step 17 of 27 in Language basics.

← Previous Next →

Records in other languages