Skip to content

Instantly share code, notes, and snippets.

@wongjiahau
Created February 15, 2019 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wongjiahau/7fe8537cf1db26cd932ce780ab74ceff to your computer and use it in GitHub Desktop.
Save wongjiahau/7fe8537cf1db26cd932ce780ab74ceff to your computer and use it in GitHub Desktop.
TeachingHaskell-Exercise 1-Answer
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