Add RAPI support to hn1
[ganeti-local] / src / Utils.hs
1 {-| Utility functions -}
2
3 module Utils where
4
5 import Data.List
6 import Data.Either
7 import System
8 import System.IO
9 import Monad
10
11 import Debug.Trace
12
13 -- | To be used only for debugging, breaks referential integrity.
14 debug :: Show a => a -> a
15 debug x = trace (show x) x
16
17 -- | Check if the given argument is Left something
18 isLeft :: Either a b -> Bool
19 isLeft val =
20     case val of
21       Left _ -> True
22       _ -> False
23
24 fromLeft :: Either a b -> a
25 fromLeft = either (\x -> x) (\_ -> undefined)
26
27 fromRight :: Either a b -> b
28 fromRight = either (\_ -> undefined) id
29
30 -- | Comma-join a string list.
31 commaJoin :: [String] -> String
32 commaJoin = intercalate ","
33
34 -- | Split a string on a separator and return an array.
35 sepSplit :: Char -> String -> [String]
36 sepSplit sep s
37     | x == "" && xs == [] = []
38     | xs == []            = [x]
39     | ys == []            = x:"":[]
40     | otherwise           = x:(sepSplit sep ys)
41     where (x, xs) = break (== sep) s
42           ys = drop 1 xs
43
44 -- | Partial application of sepSplit to @'.'@
45 commaSplit :: String -> [String]
46 commaSplit = sepSplit ','
47
48 -- | Swap a list of @(a, b)@ into @(b, a)@
49 swapPairs :: [(a, b)] -> [(b, a)]
50 swapPairs = map (\ (a, b) -> (b, a))
51
52 -- Simple and slow statistical functions, please replace with better versions
53
54 -- | Mean value of a list.
55 meanValue :: Floating a => [a] -> a
56 meanValue lst = (sum lst) / (fromIntegral $ length lst)
57
58 -- | Standard deviation.
59 stdDev :: Floating a => [a] -> a
60 stdDev lst =
61     let mv = meanValue lst
62         square = (^ (2::Int)) -- silences "defaulting the constraint..."
63         av = sum $ map square $ map (\e -> e - mv) lst
64         bv = sqrt (av / (fromIntegral $ length lst))
65     in bv
66
67
68 -- | Coefficient of variation.
69 varianceCoeff :: Floating a => [a] -> a
70 varianceCoeff lst = (stdDev lst) / (fromIntegral $ length lst)
71
72 -- | Get a Right result or print the error and exit
73 readData :: (String -> IO (Either String String)) -> String -> IO String
74 readData fn host = do
75   nd <- fn host
76   when (isLeft nd) $
77        do
78          putStrLn $ fromLeft nd
79          exitWith $ ExitFailure 1
80   return $ fromRight nd