Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- data Square = Square { squareSide :: Double }
- deriving (Show, Eq)
- data Rectangle = Rect { rectWidth :: Double , rectHeight :: Double }
- deriving (Show, Eq)
- data Circle = Circle { circleRadius :: Double }
- deriving (Show, Eq)
- data Triangle = Triangle { triangleSide1 :: Double, triangleSide2 :: Double, triangleSide3 :: Double }
- deriving (Show, Eq)
- data RegularPolygon = Poly { polySides :: Int , polySideLength :: Double }
- deriving (Show, Eq)
- --typeclass
- class Shape a where
- corners :: a -> Int
- circumference :: a -> Double
- surface :: a -> Double
- rescale :: Double -> a -> a
- instance Shape Square where
- corners (Square squareSide) = 4
- circumference (Square squareSide) = 4 * squareSide
- surface (Square squareSide) = squareSide * squareSide
- rescale factor (Square squareSide) = Square (factor * squareSide)
- instance Shape Rectangle where
- corners (Rect w h) = 4
- circumference (Rect w h) = 2 * (w + h)
- surface (Rect w h) = w * h
- rescale factor (Rect w h) = Rect (factor * w) (factor * h)
- instance Shape Circle where
- corners _ = 0
- circumference (Circle r) = 2 * pi * r
- surface (Circle r) = pi * r * r
- rescale factor (Circle r) = Circle (factor * r)
- -- Bonus
- instance Shape Triangle where
- corners _ = 3
- circumference (Triangle l1 l2 l3) = l1 + l2 + l3
- surface (Triangle l1 l2 l3) = sqrt (s * (s - l1) * (s - l2) * (s - l3))
- where
- s = (l1 + l2 + l3) / 2
- rescale factor (Triangle l1 l2 l3) = Triangle (factor * l1) (factor * l2) (factor * l3)
- -- NOTE: 'instance' takes a TYPE ctor (RegularPolygon) , whereas for the methods we pattern match of DATA (Poly) ctors
- doubleSides :: Int -> Double
- doubleSides sides = fromIntegral sides
- instance Shape RegularPolygon where
- corners (Poly sides _) = sides
- circumference (Poly sides sideLength) = doubleSides sides * sideLength
- surface (Poly sides sideLength) = (doubleSides sides * sideLength * apothem) / 2
- where
- apothem = sideLength / (2 * tan (pi / doubleSides sides))
- rescale factor (Poly sides sideLength) = Poly sides (factor * sideLength)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement