Skip to content

Instantly share code, notes, and snippets.

@buggymcbugfix
Created November 26, 2017 22:11
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 buggymcbugfix/e54d987bd78aeb763b43008ccad9e646 to your computer and use it in GitHub Desktop.
Save buggymcbugfix/e54d987bd78aeb763b43008ccad9e646 to your computer and use it in GitHub Desktop.
Command line tool to find the average (arithmetic mean) of the input
#! /usr/bin/env stack
-- stack --resolver lts-9.14 --install-ghc script --package base
import Data.Maybe (mapMaybe)
import System.Environment (getArgs)
import Text.Read (readMaybe)
{- USAGE
Pipe input:
$ echo -e "1.3\n2.7 0.8 yeah" | average
1.5999999999999999 # damn floating point
Pass input via args:
$ average 93 99 96 94 95 gunk 95 81 99 79 96 86 90 gloop 95 90 98
92.4
Beware:
$ average 7 NaN 8
NaN
-}
main = do
args <- getArgs
input <- if null args then words <$> getContents else pure args
print $ mean $ mapMaybe readMaybe input
where
mean xs = sum xs / fromIntegral (length xs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment