Skip to content

Instantly share code, notes, and snippets.

@chessai
Created April 16, 2018 19:42
Show Gist options
  • Save chessai/0c31f7f6ff781d72b4a3198e92ef742f to your computer and use it in GitHub Desktop.
Save chessai/0c31f7f6ff781d72b4a3198e92ef742f to your computer and use it in GitHub Desktop.
import Data.List (partition)
average2 :: (Fractional a) => a -> a -> a
average2 x y = (x + y) / 2
median :: Ord a => [a] -> Maybe a
median xs
| even n = Nothing
| otherwise = select (n `div` 2) xs
where
n = length xs
select :: Ord a => Int -> [a] -> Maybe a
select _ [] = Nothing
select k (x:xs) = case compare k m of
LT -> select k lt
EQ -> Just x
GT -> select (k - m - 1) gte
where
m = length lt
(lt, gte) = partition (< x) xs
main :: IO ()
main = do
let v = [1,2,3,4,5]
print $ median v
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment