haskell-phrasebook
haskell-phrasebook copied to clipboard
Defining a typeclass
We wrote this a while back to show what defining your own typeclass looks like. I'm not sure whether I like it, or whether this is actually a good topic for a Phrasebook page (because "I want to define a typeclass" is not an end goal in itself). It would be cool to include an example like this if we could figure out how to motivate it better and change the title to something that is an understandably practical objective.
class Geometry a where
area :: a -> Double
perimeter :: a -> Double
data Rectangle =
Rectangle
{ width :: Double
, height :: Double
}
deriving Show
data Circle =
Circle
{ radius :: Double
}
deriving Show
instance Geometry Rectangle where
area r = width r * height r
perimeter r = (2 * width r) + (2 * height r)
instance Geometry Circle where
area c = pi * radius c * radius c
perimeter c = 2 * pi * radius c
measure x =
do
putStrLn (show x)
putStrLn ("area: " ++ show (area x))
putStrLn ("perimeter: " ++ show (perimeter x))
main =
do
measure Rectangle{ width = 3, height = 4 }
measure Circle{ radius = 5 }
$ runhaskell classes.hs
Rectangle {width = 3.0, height = 4.0}
area: 12.0
perimeter: 14.0
Circle {radius = 5.0}
area: 78.53981633974483
perimeter: 31.41592653589793
I think having an universal construction is a good reason for defining a type class.
I feel the Geometry is a bit too trivial for the example. I think a more real world example is semigroup (though haskell cannot gurantee associativity easily).
If you like, I can make a PR on it.