Skip to content

Latest commit

 

History

History
55 lines (39 loc) · 1.6 KB

08.md

File metadata and controls

55 lines (39 loc) · 1.6 KB

Product types

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

Exercise

  • 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

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

Exercise

  • Write the extractor functions for the Ship type.

Record syntax

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 }

Exercise

  • Rewrite the Ship type using record syntax.