packages feed

nptools-0.5.0: mean.hs

import System.Environment
import Control.Monad
import Data.Ratio
import Numeric

data P = P !Integer !Integer

mean :: [Integer] -> Rational
mean = divP . foldl f (P 0 0) where
  f (P m s) i = P (i + m) (1 + s)
  divP (P m s) = m % s

showRat :: Rational -> String
showRat x = showFFloat Nothing (fromRat x :: Double) ""

main :: IO ()
main = do
  argc <- length `fmap` getArgs
  when (argc /= 0) . fail . unlines $ ["`mean' does not expect arguments."
                                      ,"It reads numbers from stdin and finally prints the mean"]
  putStrLn . showRat         -- format the output
           . mean            -- take the mean
           . map readI       -- turns numbers into integers
           . concatMap words -- split words
           . lines           -- split lines
           =<< getContents   -- reads stdin
  where readI :: String -> Integer
        readI = read