Utils.hs 2.2 KB
Newer Older
Iustin Pop's avatar
Iustin Pop committed
1
2
{-| Utility functions -}

3
4
5
6
7
8
9
10
11
12
13
module Ganeti.HTools.Utils
    (
      debug
    , isLeft
    , fromLeft
    , fromRight
    , sepSplit
    , swapPairs
    , varianceCoeff
    , readData
    ) where
Iustin Pop's avatar
Iustin Pop committed
14

Iustin Pop's avatar
Iustin Pop committed
15
import Data.Either
16
17
import Data.List
import Monad
Iustin Pop's avatar
Iustin Pop committed
18
19
import System
import System.IO
Iustin Pop's avatar
Iustin Pop committed
20
21
22
23
24
25
26

import Debug.Trace

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

Iustin Pop's avatar
Iustin Pop committed
27
28
29
30
31
32
33
34
35
36
37
38
39
-- | Check if the given argument is Left something
isLeft :: Either a b -> Bool
isLeft val =
    case val of
      Left _ -> True
      _ -> False

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

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

Iustin Pop's avatar
Iustin Pop committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
-- | Comma-join a string list.
commaJoin :: [String] -> String
commaJoin = intercalate ","

-- | Split a string on a separator and return an array.
sepSplit :: Char -> String -> [String]
sepSplit sep s
    | x == "" && xs == [] = []
    | xs == []            = [x]
    | ys == []            = x:"":[]
    | otherwise           = x:(sepSplit sep ys)
    where (x, xs) = break (== sep) s
          ys = drop 1 xs

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

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

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

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

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

-- | Coefficient of variation.
varianceCoeff :: Floating a => [a] -> a
varianceCoeff lst = (stdDev lst) / (fromIntegral $ length lst)
Iustin Pop's avatar
Iustin Pop committed
80
81
82
83
84
85
86
87
88
89

-- | Get a Right result or print the error and exit
readData :: (String -> IO (Either String String)) -> String -> IO String
readData fn host = do
  nd <- fn host
  when (isLeft nd) $
       do
         putStrLn $ fromLeft nd
         exitWith $ ExitFailure 1
  return $ fromRight nd