Simple Algebraic Data Types
Prev: Products and Coproducts Next: Functors
Prev: Products and Coproducts Next: Functors
Exercises
- Show the isomorphism between
Maybe aandEither () a. - Here’s a sum type defined in Haskell:
data Shape = Circle Float
| Rect Float FloatWhen we want to define a function like area that acts on a Shape, we do it by pattern matching on the two constructors:
area :: Shape -> Float
area (Circle r) = pi * r * r
area (Rect d h) = d * hImplement Shape in C++ or Java as an interface and create two classes: Circle and Rect. Implement area as a virtual function.
- Continuing with the previous example: We can easily add a new function
circthat calculates the circumference of aShape. We can do it without touching the definition ofShape:
circ :: Shape -> Float
circ (Circle r) = 2.0 * pi * r
circ (Rect d h) = 2.0 * (d + h)Add circ to your C++ or Java implementation. What parts of the original code did you have to touch?
- Continuing further: Add a new shape,
Square, toShapeand make all the necessary updates. What code did you have to touch in Haskell vs. C++ or Java? (Even if you’re not a Haskell programmer, the modifications should be pretty obvious.) - Show that holds for types (up to isomorphism). Remember that corresponds to
Bool, according to our translation table.