Created
April 16, 2018 19:42
-
-
Save chessai/0c31f7f6ff781d72b4a3198e92ef742f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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