Hey guys,<br><br>It's a dumb question but I'd like to know a right answer...<br>Let's say we have some geometry data that can be Sphere, Cylinder, Circle and so on. We can implement it as new data type plus a bunch of functions that work on this data:<br>
<br>data Geometry = Sphere Position Radius<br> | Cylinder Position Radius Height<br> | Circle Position Radius<br> deriving (Show)<br>
<br>perimeter (Sphere _ r) = 0.0<br>perimeter (Cylinder _ r h) = 0.0<br>perimeter (Circle _ r) = 2.0 * pi * r<br><br>Perimeter doesn't make sense for Sphere or Cylinder. So we could define a type class for objects that have perimeter and make an instance of it only for Circle (data Circle = Circle Position Radius). Make sense. But these three functions above have desired behaviour. If user has a list of objects like [Sphere, Circle, Circle, Cylinder] he would like to calculate perimeters of each object using map perimerer list (in this case we also have to modify Geometry data type).<br>
So we could make instances of "perimeter" type class for all objects and return zero in case if perimeter doesn't make sense.<br>Same as previous version but with typeclasses and with additional constructors (constructors for each type of object + constructors in Geometry data). Looks a bit overcomplicated.<br>
Any reasons to use type classes in this case? Maybe there is something I'm missing?<br><br>Cheers,<br>-O<br>