The classic shape example, adapted for Haskell
Saturday, March 15th, 2008 by Matthew ElderHello, here is a reproduction of the classic Shape example adapted for haskell (The equivalent of “hello world” in the OOP world).
With haskell classes and three different data types (think Java interfaces)
-- define the shape data types
data Triangle = Triangle
data Square = Square
data Octagon = Octagon
class Shape s where
sides :: s -> Integer
instance Shape Triangle where
sides _ = 3
instance Shape Square where
sides _ = 4
instance Shape Octagon where
sides _ = 8
GHCi output
*Main> sides Triangle
3
*Main> sides Square
4
*Main> sides Octagon
8
With one haskell datatype and runtime pattern matching (think erlang or “parametric polymorphism”)
-- define the instances of shape
data Shape =
Triangle |
Square |
Octagon
sides Triangle = 3
sides Square = 4
sides Octagon = 8
GHCi output
*Main> sides Triangle
3
*Main> sides Square
4
*Main> sides Octagon
8
Which do you like better?












