Skip to content

Instantly share code, notes, and snippets.

@lambda-fairy
Created September 3, 2012 04:53
Show Gist options
  • Save lambda-fairy/3606778 to your computer and use it in GitHub Desktop.
Save lambda-fairy/3606778 to your computer and use it in GitHub Desktop.
Solution for Lab 6 Exercise 2
-- | Solution for Lab 6 Exercise 2
module Temperatures where
import Control.Applicative
import Control.Arrow
import Data.Char
import Text.Printf
type Row = [Double]
data Result = Result
{ resultMin :: Double
, resultMax :: Double
, resultMean :: Double
}
main :: IO ()
main = interact (regurgitate . digest . consume)
consume :: String -> [Row]
consume = map (map (read . stripSpaces) . wordsOn (== ',')) . lines
digest :: [Row] -> ([Result], Double)
digest = map (Result <$> minimum <*> maximum <*> mean) &&& (mean . map mean)
mean :: Fractional a => [a] -> a
mean = (/) <$> sum <*> fromIntegral . length
regurgitate :: ([Result], Double) -> String
regurgitate (results, overallMean) = unlines $ [header] ++ body ++ [footer]
where
header = " Day Min Max Avg"
body = zipWith showResult [1..] results
showResult day (Result mi ma me) = printf " %3d %5.1f %5.1f %5.1f" (day :: Int) mi ma me
footer = printf " Average temperature for the month: %5.1f" overallMean
wordsOn :: (a -> Bool) -> [a] -> [[a]]
wordsOn p xs = case dropWhile p xs of
[] -> []
xs' -> w : wordsOn p xs''
where (w, xs'') = break p xs'
stripSpaces :: String -> String
stripSpaces = reverse . dropWhile isSpace . reverse . dropWhile isSpace
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment