Created
February 15, 2019 05:17
-
-
Save wongjiahau/7fe8537cf1db26cd932ce780ab74ceff to your computer and use it in GitHub Desktop.
TeachingHaskell-Exercise 1-Answer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment