Skip to content

Instantly share code, notes, and snippets.

@ijt
Created February 14, 2012 08:24
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 ijt/1824798 to your computer and use it in GitHub Desktop.
Save ijt/1824798 to your computer and use it in GitHub Desktop.
Print the median of a newline-separated list of numbers
#!/usr/bin/env runhaskell
import Data.List (sort, (\\))
import Test.QuickCheck (Property, (==>))
main = interact (showLn . median . map read . lines)
showLn :: Show a => a -> String
showLn x = show x ++ "\n"
median :: [Float] -> Float
median xs | odd (length xs) = sort xs !! (length xs `div` 2)
| otherwise = 0.5 * (sorted !! i + sorted !! (i + 1))
where sorted = sort xs
i = (length xs `div` 2) - 1
-- The median of a list of repeated x is just x.
prop_sameNumber :: Int -> Float -> Property
prop_sameNumber n x = n > 0 && n < 100 ==> median (replicate n x) == x
-- The median of [-n..n] is 0 for any n.
-- This exercises the odd length case.
prop_increasing :: Int -> Property
prop_increasing n = n >= 0 && n < 100 ==> median (map fromIntegral [-n..n]) == 0.0
-- The median of [-n..n] with 0 removed is 0 for any n.
-- This exercises the even length case.
prop_increasing2 :: Int -> Property
prop_increasing2 n = n > 0 && n < 100 ==> median (map fromIntegral ([-n..n] \\ [0])) == 0.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment