----------------------------------------------------------------------- -- Shape example, from Haskell craft, Ch 14 -- Added triangle constructor to Shape1 -- -- 21 June 2001 ----------------------------------------------------------------------- module Shape2 where -- A shape in a simple geometrical program is either a circle or a -- rectangle. These alternatives are given by the type data Shape = Circle Float | Rectangle Float Float | Triangle Float Float Float --<<<< shape1 = Circle 3.0 shape2 = Rectangle 45.9 87.6 -- Pattern matching allows us to define functions by cases, as in, isRound :: Shape -> Bool isRound (Circle _) = True isRound (Rectangle _ _) = False isRound (Triangle _ _ _) = False --<<<< -- and also lets us use the components of the elements: area :: Shape -> Float area (Circle r) = pi*r*r area (Rectangle h w) = h*w area (Triangle x y z) = sqrt(s*(s-x)*(s-y)*(s-z)) --<<<< where s = (x+y+z)/2 --<<<< perimeter :: Shape -> Float perimeter (Circle r) = 2*pi*r perimeter (Rectangle h w) = 2*(h+w) perimeter (Triangle x y z) = x+y+z --<<<<