Guest User

Untitled

a guest
Feb 17th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. data Shape
  2. = Circle Float
  3. | Square Float
  4. | Rectangle Float Float
  5. | Null
  6. deriving (Show)
  7.  
  8. main :: IO ()
  9. main = do
  10. -- Read contents from shape.txt
  11. contents <- readFile "shape.txt"
  12.  
  13. -- Parse shapes
  14. let shapes = map toShape (lines contents)
  15.  
  16. -- Compute areas
  17. let areas = map calculateArea shapes
  18.  
  19. putStrLn "AREAS:"
  20. putStrLn (concatMap (\x -> show x ++"\n") areas)
  21.  
  22. -- Compute counts
  23. let (circleCount, squareCount, rectangleCount, nullCount) =
  24. foldl
  25. (\(c,s,r,n) nextShape ->
  26. case nextShape of
  27. Circle{} -> (c+1,s,r,n)
  28. Square{} -> (c,s+1,r,n)
  29. Rectangle{} -> (c,s,r+1,n)
  30. Null{} -> (c,s,r,n+1))
  31. (0,0,0,0)
  32. shapes
  33.  
  34. putStrLn "\nCOUNTS:"
  35. putStrLn ("Circle " ++ show circleCount)
  36. putStrLn ("Square " ++ show squareCount)
  37. putStrLn ("Rectangle " ++ show rectangleCount)
  38. putStrLn ("NULL " ++ show nullCount)
  39.  
  40.  
  41. toShape :: String -> Shape
  42. toShape row =
  43. case words row of
  44. ["Circle", radius] ->
  45. Circle (readFloat radius)
  46.  
  47. ["Square", side] ->
  48. Square (readFloat side)
  49.  
  50. ["Rectangle", height, width] ->
  51. Rectangle (readFloat height) (readFloat width)
  52.  
  53. ["NULL"] ->
  54. Null
  55.  
  56. calculateArea :: Shape -> Float
  57. calculateArea s = case s of
  58. Circle r -> 3.142 * (r ^ 2)
  59. Square s -> s * s
  60. Rectangle h w -> h * w
  61. Null -> 0.0
  62.  
  63.  
  64. readFloat :: String -> Float
  65. readFloat = read
Add Comment
Please, Sign In to add comment