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
data Roast = Roastdeclares three fields, so a name likebagsOnHandbecomes a function from aRoastto that one field.houseis built by naming fields, which is why their order inside the braces is free.sell n r = r { bagsOnHand = bagsOnHand r - n }returns a copy with one field replaced, leavinghouseuntouched.
Keywords and builtins used here
IOIntRoastShowStringdataderivinghouselabelmainsell
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.
Step 2 of 3 in Types & records, step 17 of 27 in Language basics.