Utils.hs 4.95 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
15
16
17
18
19
20
21
22
23
24
25
26
    , combineEithers
    , ensureEitherList
    , eitherListHead
    , readEitherString
    , parseEitherList
    , loadJSArray
    , fromObj
    , getStringElement
    , getIntElement
    , getListElement
    , concatEitherElems
    , applyEither1
    , applyEither2
27
    ) where
Iustin Pop's avatar
Iustin Pop committed
28

Iustin Pop's avatar
Iustin Pop committed
29
import Data.Either
30
31
import Data.List
import Monad
Iustin Pop's avatar
Iustin Pop committed
32
33
import System
import System.IO
34
35
import Text.JSON
import Text.Printf (printf)
Iustin Pop's avatar
Iustin Pop committed
36
37
38
39
40
41
42

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
43
44
45
46
47
48
49
50
51
52
53
54
55
-- | 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
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
-- | 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
96
97
98
99
100
101
102
103
104
105

-- | 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188

{-- Our cheap monad-like stuff.

Thi is needed since Either e a is already a monad instance somewhere
in the standard libraries (Control.Monad.Error) and we don't need that
entire thing.

-}
combineEithers :: (Either String a)
               -> (a -> Either String b)
               -> (Either String b)
combineEithers (Left s) _ = Left s
combineEithers (Right s) f = f s

ensureEitherList :: [Either String a] -> Either String [a]
ensureEitherList lst =
    foldr (\elem accu ->
               case (elem, accu) of
                 (Left x, _) -> Left x
                 (_, Left x) -> Left x -- should never happen
                 (Right e, Right a) -> Right (e:a)
          )
    (Right []) lst

eitherListHead :: Either String [a] -> Either String a
eitherListHead lst =
    case lst of
      Left x -> Left x
      Right (x:_) -> Right x
      Right [] -> Left "List empty"

readEitherString :: JSValue -> Either String String
readEitherString v =
    case v of
      JSString s -> Right $ fromJSString s
      _ -> Left "Wrong JSON type"

parseEitherList :: (JSObject JSValue -> Either String String)
          -> [JSObject JSValue]
          -> Either String String
parseEitherList fn idata =
    let ml = ensureEitherList $ map fn idata
    in ml `combineEithers` (Right . unlines)

loadJSArray :: String -> Either String [JSObject JSValue]
loadJSArray s = resultToEither $ decodeStrict s

fromObj :: JSON a => String -> JSObject JSValue -> Either String a
fromObj k o =
    case lookup k (fromJSObject o) of
      Nothing -> Left $ printf "key '%s' not found" k
      Just val -> resultToEither $ readJSON val

getStringElement :: String -> JSObject JSValue -> Either String String
getStringElement = fromObj

getIntElement :: String -> JSObject JSValue -> Either String Int
getIntElement = fromObj

getListElement :: String -> JSObject JSValue
               -> Either String [JSValue]
getListElement = fromObj

concatEitherElems :: Either String String
            -> Either String String
            -> Either String String
concatEitherElems = applyEither2 (\x y -> x ++ "|" ++ y)

applyEither1 :: (a -> b) -> Either String a -> Either String b
applyEither1 fn a =
    case a of
      Left x -> Left x
      Right y -> Right $ fn y

applyEither2 :: (a -> b -> c)
       -> Either String a
       -> Either String b
       -> Either String c
applyEither2 fn a b =
    case (a, b) of
      (Right x, Right y) -> Right $ fn x y
      (Left x, _) -> Left x
      (_, Left y) -> Left y