Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- data Shape
- = Circle Float
- | Square Float
- | Rectangle Float Float
- | Null
- deriving (Show)
- main :: IO ()
- main = do
- -- Read contents from shape.txt
- contents <- readFile "shape.txt"
- -- Parse shapes
- let shapes = map toShape (lines contents)
- -- Compute areas
- let areas = map calculateArea shapes
- putStrLn "AREAS:"
- putStrLn (concatMap (\x -> show x ++"\n") areas)
- -- Compute counts
- let (circleCount, squareCount, rectangleCount, nullCount) =
- foldl
- (\(c,s,r,n) nextShape ->
- case nextShape of
- Circle{} -> (c+1,s,r,n)
- Square{} -> (c,s+1,r,n)
- Rectangle{} -> (c,s,r+1,n)
- Null{} -> (c,s,r,n+1))
- (0,0,0,0)
- shapes
- putStrLn "\nCOUNTS:"
- putStrLn ("Circle " ++ show circleCount)
- putStrLn ("Square " ++ show squareCount)
- putStrLn ("Rectangle " ++ show rectangleCount)
- putStrLn ("NULL " ++ show nullCount)
- toShape :: String -> Shape
- toShape row =
- case words row of
- ["Circle", radius] ->
- Circle (readFloat radius)
- ["Square", side] ->
- Square (readFloat side)
- ["Rectangle", height, width] ->
- Rectangle (readFloat height) (readFloat width)
- ["NULL"] ->
- Null
- calculateArea :: Shape -> Float
- calculateArea s = case s of
- Circle r -> 3.142 * (r ^ 2)
- Square s -> s * s
- Rectangle h w -> h * w
- Null -> 0.0
- readFloat :: String -> Float
- readFloat = read
Add Comment
Please, Sign In to add comment