Category Theory for Programmers Chapter 6: Simple Algebraic Data Types
-
Show the isomorphism between
Maybe aandEither () a.maybeToEither :: Maybe a -> Either () a maybeToEither None = Left () maybeToEither Just x = Right x eitherToMaybe :: Either () a -> Maybe a eitherToMaybe Left _ = None eitherToMaybe Right x = Just x -
Implement
Shapein C++ or Java as an interface and create two classes:CircleandRect. Implementareaas a virtual function.public class HelloWorld { interface Shape { double area(); } static class Circle implements Shape { final double radius; Circle(double radius) { this.radius = radius; } @Override public double area() { return Math.PI * radius * radius; } } static class Rect implements Shape { final double height; final double width; Rect(double height, double width) { this.height = height; this.width = width; } @Override public double area() { return height * width; } } public static void printShape(Shape shape) { System.out.println(shape.area()); } public static void main(String[] args) { printShape(new Circle(5.0)); printShape(new Rect(5.0, 5.0)); } } -
Add
circto your C++ or Java implementation. What parts of the original code did you have to touch?Add
double circ();to the interface, then implement it in both the subclasses. -
Adding
Squarein Java is just creating a new subclass. -
a + ais represented byEither a aand2 * acan be represented by(Bool, a). This works because you can assign eitherLeftorRightone of the two values ofBoolso then you create the mappingsLeft a => (true, a)andRight a => (false, a).