Skip to content

Instantly share code, notes, and snippets.

@kolharsam
Created Mar 9, 2020
Embed
What would you like to do?
Cassidy's Interview Question - Mar 09/03/2020
import qualified Data.List as List
listSum :: (Num a) => [a] -> a
listSum [] = 0
listSum xs = foldr (+) 0 xs
getLength :: (Num a) => [a] -> a
getLength xs = foldr (\_ acc -> acc + 1) 0 xs
myGroup :: (Num a, Eq a, Ord a) => [a] -> [(a, Int)]
myGroup xs = map (\x -> (List.head x, List.length x)) . List.group . List.sort $ xs
getFirst :: (a, Int) -> a
getFirst (x, y) = x
mean :: (Num a, Fractional a, Ord a) => [a] -> a
mean [] = 0
mean xs = (listSum xs) / (getLength xs)
median :: (Num a, Fractional a, Ord a) => [a] -> a
median [] = 0
median xs = do
let sortedList = List.sort xs
let listLen = List.length xs
if even listLen
then (sortedList !! (div listLen 2))
else (sortedList !! (div (listLen+1) 2))
mode :: (Num a, Fractional a, Ord a) => [a] -> a
mode [] = 0
mode xs = getFirst . List.head . List.reverse . List.sortBy (\(_, c) (_, d) -> compare c d) . myGroup $ xs
getMeanMedianMode :: (Num a, Fractional a, Ord a) => [a] -> (a, a, a)
getMeanMedianMode xs = (mean xs, median xs, mode xs)
main :: IO()
main = do
let list = [1,2,3,5,5,5,5,5,5,2,1,2,1]
print (getMeanMedianMode list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment