----------------------------------------------------------------------- -- Shape example, from Haskell craft, Ch 14 -- Different types for each sort of shape: each instance -- of the Shape type class. Based on Shape2. -- -- 21 June 2001 ----------------------------------------------------------------------- module Shape3 where -- There is no longer a type of Shapes, rather there are operations -- which can be applied to each sort of shape; collect these in a -- class declaration, replacing the Shape type by the type variable -- a bound in the class declaratoion. class Shape a where isRound :: a -> Bool area :: a -> Float perimeter :: a -> Float -- Pull the single data type into three separate types... data Circle = Circle Float data Rectangle = Rectangle Float Float data Triangle = Triangle Float Float Float shape1 = Circle 3.0 shape2 = Rectangle 45.9 87.6 -- Reorganise the definitions, organising by sort of shape rather -- than by function. This is simply a matter of cutting and pasting -- lines in the file. instance Shape Circle where isRound (Circle _) = True area (Circle r) = pi*r*r perimeter (Circle r) = 2*pi*r instance Shape Rectangle where isRound (Rectangle _ _) = False area (Rectangle h w) = h*w perimeter (Rectangle h w) = 2*(h+w) instance Shape Triangle where isRound (Triangle _ _ _) = False area (Triangle x y z) = sqrt(s*(s-x)*(s-y)*(s-z)) where s = (x+y+z)/2 perimeter (Triangle x y z) = x+y+z