Initial import
[ganeti-local] / src / Utils.hs
1 {-| Utility functions -}
2
3 module Utils where
4
5 import Data.List
6
7 import Debug.Trace
8
9 -- | To be used only for debugging, breaks referential integrity.
10 debug :: Show a => a -> a
11 debug x = trace (show x) x
12
13 -- | Comma-join a string list.
14 commaJoin :: [String] -> String
15 commaJoin = intercalate ","
16
17 -- | Split a string on a separator and return an array.
18 sepSplit :: Char -> String -> [String]
19 sepSplit sep s
20     | x == "" && xs == [] = []
21     | xs == []            = [x]
22     | ys == []            = x:"":[]
23     | otherwise           = x:(sepSplit sep ys)
24     where (x, xs) = break (== sep) s
25           ys = drop 1 xs
26
27 -- | Partial application of sepSplit to @'.'@
28 commaSplit :: String -> [String]
29 commaSplit = sepSplit ','
30
31 -- | Swap a list of @(a, b)@ into @(b, a)@
32 swapPairs :: [(a, b)] -> [(b, a)]
33 swapPairs = map (\ (a, b) -> (b, a))
34
35 -- Simple and slow statistical functions, please replace with better versions
36
37 -- | Mean value of a list.
38 meanValue :: Floating a => [a] -> a
39 meanValue lst = (sum lst) / (fromIntegral $ length lst)
40
41 -- | Standard deviation.
42 stdDev :: Floating a => [a] -> a
43 stdDev lst =
44     let mv = meanValue lst
45         square = (^ (2::Int)) -- silences "defaulting the constraint..."
46         av = sum $ map square $ map (\e -> e - mv) lst
47         bv = sqrt (av / (fromIntegral $ length lst))
48     in bv
49
50
51 -- | Coefficient of variation.
52 varianceCoeff :: Floating a => [a] -> a
53 varianceCoeff lst = (stdDev lst) / (fromIntegral $ length lst)