Sum and product types together are called Algebraic Data Types.
data Shape = Triangle {a :: Double, b :: Double, c :: Double}
| Rectangle {width :: Double, height :: Double}
The Shape type is an algebraic data type. Different types of shapes are represented as sum types. The properties of different shapes are represented as product types.
- Write a type called Vehicle that has the following data constructors: Ship, Car, Plane. Try to come up with different fields for each vehicle type. Use the types from the previous lecture.
Let's revisit pattern matching for algebraic data types.
perimeter :: Shape -> Double
perimeter (Triangle a b c) = a + b + c
perimeter (Rectangle width height) = 2 * (width + height)
The single perimeter function can work on all kinds of shape values.
- Write the price :: Vehicle -> Double function.
We have used pattern matching to deconstruct function parameters so far. There are a few other places where pattern matching can be used. One of these is a case expression.
report :: Shape -> String
report shape = let perimeter = case shape of
(Triangle a b c) -> a + b + c
(Rectangle width height) -> 2 * (width + height)
in "perimeter of shape: " ++ show perimeter
Since case is an expression, the right hand side of all cases should have the same type.
- What is the type of the perimeter value and the right hand side of each case in the report function?
- Rewrite the price function using case expressions.
- How would you model things around you using algebraic data types? Pick something interesting in your environment and model it using algebraic data types.