Advertisement
VladNitu

Shapes_FP_Vlad

Feb 24th, 2024
884
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. data Square = Square { squareSide :: Double }
  2.   deriving (Show, Eq)
  3.  
  4. data Rectangle = Rect { rectWidth :: Double , rectHeight :: Double }
  5.   deriving (Show, Eq)
  6.  
  7. data Circle = Circle { circleRadius :: Double }
  8.   deriving (Show, Eq)
  9.  
  10. data Triangle = Triangle { triangleSide1 :: Double, triangleSide2 :: Double, triangleSide3 :: Double }
  11.   deriving (Show, Eq)
  12.  
  13. data RegularPolygon = Poly { polySides :: Int , polySideLength :: Double }
  14.   deriving (Show, Eq)
  15.  
  16.  
  17. --typeclass
  18. class Shape a where
  19.   corners :: a -> Int
  20.   circumference :: a -> Double
  21.   surface :: a -> Double
  22.   rescale :: Double -> a -> a
  23.  
  24. instance Shape Square where
  25.   corners (Square squareSide) = 4
  26.   circumference (Square squareSide) = 4 * squareSide
  27.   surface (Square squareSide) = squareSide * squareSide
  28.   rescale factor (Square squareSide) = Square (factor * squareSide)
  29.  
  30. instance Shape Rectangle where
  31.   corners (Rect w h) = 4
  32.   circumference (Rect w h) = 2 * (w + h)
  33.   surface (Rect w h) = w * h
  34.   rescale factor (Rect w h) = Rect (factor * w) (factor * h)
  35.  
  36. instance Shape Circle where
  37.   corners _ = 0
  38.   circumference (Circle r) = 2 * pi * r
  39.   surface (Circle r) = pi * r * r
  40.   rescale factor (Circle r) = Circle (factor * r)
  41.  
  42. -- Bonus
  43. instance Shape Triangle where
  44.   corners _ = 3
  45.   circumference (Triangle l1 l2 l3) = l1 + l2 + l3
  46.   surface (Triangle l1 l2 l3) = sqrt (s * (s - l1) * (s - l2) * (s - l3))
  47.     where
  48.       s = (l1 + l2 + l3) / 2
  49.   rescale factor (Triangle l1 l2 l3) = Triangle (factor * l1) (factor * l2) (factor * l3)
  50.  
  51. -- NOTE: 'instance' takes a TYPE ctor (RegularPolygon) , whereas for the methods we pattern match of DATA (Poly) ctors
  52.  
  53.  
  54. doubleSides :: Int -> Double
  55. doubleSides sides = fromIntegral sides
  56.  
  57. instance Shape RegularPolygon where
  58.   corners (Poly sides _) = sides
  59.   circumference (Poly sides sideLength) = doubleSides sides * sideLength
  60.   surface (Poly sides sideLength) = (doubleSides sides * sideLength * apothem) / 2
  61.     where
  62.       apothem = sideLength / (2 * tan (pi / doubleSides sides))
  63.   rescale factor (Poly sides sideLength) = Poly sides (factor * sideLength)
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement