Statistics
| Branch: | Tag: | Revision:

root / src / Utils.hs @ 1b7cf8ca

History | View | Annotate | Download (1.7 kB)

1
{-| Utility functions -}
2

    
3
module Utils where
4

    
5
import Data.List
6
import Data.Either
7

    
8
import Debug.Trace
9

    
10
-- | To be used only for debugging, breaks referential integrity.
11
debug :: Show a => a -> a
12
debug x = trace (show x) x
13

    
14
-- | Check if the given argument is Left something
15
isLeft :: Either a b -> Bool
16
isLeft val =
17
    case val of
18
      Left _ -> True
19
      _ -> False
20

    
21
fromLeft :: Either a b -> a
22
fromLeft = either (\x -> x) (\_ -> undefined)
23

    
24
fromRight :: Either a b -> b
25
fromRight = either (\_ -> undefined) id
26

    
27
-- | Comma-join a string list.
28
commaJoin :: [String] -> String
29
commaJoin = intercalate ","
30

    
31
-- | Split a string on a separator and return an array.
32
sepSplit :: Char -> String -> [String]
33
sepSplit sep s
34
    | x == "" && xs == [] = []
35
    | xs == []            = [x]
36
    | ys == []            = x:"":[]
37
    | otherwise           = x:(sepSplit sep ys)
38
    where (x, xs) = break (== sep) s
39
          ys = drop 1 xs
40

    
41
-- | Partial application of sepSplit to @'.'@
42
commaSplit :: String -> [String]
43
commaSplit = sepSplit ','
44

    
45
-- | Swap a list of @(a, b)@ into @(b, a)@
46
swapPairs :: [(a, b)] -> [(b, a)]
47
swapPairs = map (\ (a, b) -> (b, a))
48

    
49
-- Simple and slow statistical functions, please replace with better versions
50

    
51
-- | Mean value of a list.
52
meanValue :: Floating a => [a] -> a
53
meanValue lst = (sum lst) / (fromIntegral $ length lst)
54

    
55
-- | Standard deviation.
56
stdDev :: Floating a => [a] -> a
57
stdDev lst =
58
    let mv = meanValue lst
59
        square = (^ (2::Int)) -- silences "defaulting the constraint..."
60
        av = sum $ map square $ map (\e -> e - mv) lst
61
        bv = sqrt (av / (fromIntegral $ length lst))
62
    in bv
63

    
64

    
65
-- | Coefficient of variation.
66
varianceCoeff :: Floating a => [a] -> a
67
varianceCoeff lst = (stdDev lst) / (fromIntegral $ length lst)