Continuing our journey of abstract data types, today we will look into product types. Values of product types contain several other values called fields.
data Person = P String String Int
yoda = P "Yoda" "Dagobah" 900
Every value of type Person is created using the data constructor P followed by three fields:
- a value of type String representing the name
- another value of type String representing the address
- and a value of type Int representing the age of the person
- Start ghci and have a look at the type of the P data constructor.
- Define a sum type called Propulsion with possible values: Wind, Diesel.
- Define a type called Ship that has the following properties: propulsion system, length in feets, passenger capacity.
Pattern matching works on product types just as it works on sum types.
name :: Person -> String
name (P name address age) = name
address :: Person -> String
address (P name address age) = address
age :: Person -> Int
age (P name address age) = age
- Write the extractor functions for the Ship type.
In the previous examples we saw functions that extract one field of a product type. It would be really annoying to define a function for each field in a large data structure. Fortunately this can be solved using Record syntax. Using record syntax ghc is going to generate these functions for you.
data Person = P { name :: String, address :: String, age :: Int }
- Rewrite the Ship type using record syntax.