Created
June 6, 2013 08:03
-
-
Save WillNess/5720014 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| === Dynamic dispatch mechanism of OOP === | |
| '''Existential types''' in conjunction with type classes can be used | |
| to emulate the dynamic dispatch mechanism of object oriented programming | |
| languages. To illustrate this concept I show how a classic example from | |
| object oriented programming can be encoded in Haskell. | |
| <haskell> | |
| class ShapeClass a where | |
| perimeter :: a -> Double | |
| area :: a -> Double | |
| data ShapeObj = forall a. ShapeClass a => ShapeTag a | |
| type Radius = Double | |
| type Side = Double | |
| data CircleObj = CircleTag Radius | |
| data RectangleObj = RectangleTag Side Side | |
| data SquareObj = SquareTag Side | |
| instance ShapeClass CircleObj where | |
| perimeter (CircleTag r) = 2 * pi * r | |
| area (CircleTag r) = pi * r * r | |
| instance ShapeClass RectangleObj where | |
| perimeter (RectangleTag x y) = 2*(x + y) | |
| area (RectangleTag x y) = x * y | |
| instance ShapeClass SquareObj where | |
| perimeter (SquareTag sd) = 4*sd | |
| area (SquareTag sd) = sd*sd | |
| instance ShapeClass ShapeObj where | |
| perimeter (ShapeTag sp) = perimeter sp | |
| area (ShapeTag sp) = area sp | |
| -- | |
| -- Smart constructor | |
| -- | |
| circle :: Radius -> ShapeObj | |
| circle r = ShapeTag (CircleTag r) | |
| rectangle :: Side -> Side -> ShapeObj | |
| rectangle x y = ShapeTag (RectangleTag x y) | |
| square :: Side -> ShapeObj | |
| square s = ShapeTag (SquareTag s) | |
| shapes :: [ShapeObj] | |
| shapes = [circle 2.4, rectangle 3.1 4.4, square 2.1] | |
| </haskell> | |
| (You may see other [[Smart constructors]] for other purposes). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment