You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
classGeometryawherearea::a->Doubleperimeter::a->DoubledataRectangle=Rectangle{width::Double
, height::Double}derivingShowdataCircle=Circle{radius::Double}derivingShowinstanceGeometryRectanglewhere
area r = width r * height r
perimeter r = (2* width r) + (2* height r)
instanceGeometryCirclewhere
area c =pi* radius c * radius c
perimeter c =2*pi* radius c
measure x =doputStrLn (show x)
putStrLn ("area: "++show (area x))
putStrLn ("perimeter: "++show (perimeter x))
main =do
measure Rectangle{ width =3, height =4 }
measure Circle{ radius =5 }
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).
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.
The text was updated successfully, but these errors were encountered: