Skip to content

Latest commit

 

History

History
57 lines (43 loc) · 1.87 KB

09.md

File metadata and controls

57 lines (43 loc) · 1.87 KB

Algebraic Data Types

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.

Exercise

  • 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.

General pattern matching

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.

Exercise

  • Write the price :: Vehicle -> Double function.

Case expressions

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.

Exercise

  • 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.