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

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

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

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
28
29
30
31
32
33
34
35
36
37
38
39
40
-- | 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
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
80
-- | 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
81
82
83
84
85
86
87
88
89
90

-- | 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