module Maskell.Stats where

import Control.Monad
import Data.List
import Data.Maybe

test_mcmath = do
  putStrLn "hello from Mcmath"


{-|
The `prank' function calculates percentile ranks of a list of floats.
 prank [23.0, 20.0, 20.0,  57.0, 46.0]
-}
prank :: [Float] -> [Float]
prank arr =
  map score  arr
  where
    len p v = fromIntegral $ length $ filter (p v) arr
    n = fromIntegral $ length arr
    score v = ((len (>) v)  + 0.5 * (len (==) v))/n



data1 = [23.0, 20.0, 20.0,  57.0, 46.0]
testPrank = prank data1

prankM :: [Maybe Float] -> [Maybe Float]
prankM arrM =
  rebuild [] pranks arrM
  where
    pranks = prank $ catMaybes arrM
    rebuild acc _ [] = acc
    rebuild acc (p:ps) (m:ms) =
      if isJust m
      then rebuild (acc ++ [Just p]) ps ms
      else rebuild (acc ++ [Nothing]) (p:ps) ms
  

testPrankM = prankM [Just 23.0, Just 20.0, Just 20.0,  Nothing, Just 57.0, Just 46.0]


-- | on a sorted list
median' xs | null xs  = Nothing
          | odd  len = Just $ xs !! mid
          | even len = Just $ meanMedian
                where  len = length xs
                       mid = len `div` 2
                       meanMedian = (xs !! mid + xs !! (mid-1)) / 2
median' :: Fractional a => [a] -> Maybe a

-- | on an unsorted list
median xs = median' $ sort xs

mmedian xs = median $ catMaybes xs
  
mean :: (Fractional a) => [a] -> a
mean [] = 0
mean xs = sum xs / Data.List.genericLength xs

mmean xs = mean $ catMaybes xs
