1 {-| Utility functions -}
3 module Ganeti.HTools.Utils
21 import qualified Text.JSON as J
22 import Text.Printf (printf)
24 import Ganeti.HTools.Types
30 -- | To be used only for debugging, breaks referential integrity.
31 debug :: Show a => a -> a
32 debug x = trace (show x) x
36 -- | Comma-join a string list.
37 commaJoin :: [String] -> String
38 commaJoin = intercalate ","
40 -- | Split a string on a separator and return an array.
41 sepSplit :: Char -> String -> [String]
43 | x == "" && xs == [] = []
46 | otherwise = x:(sepSplit sep ys)
47 where (x, xs) = break (== sep) s
50 -- | Partial application of sepSplit to @'.'@
51 commaSplit :: String -> [String]
52 commaSplit = sepSplit ','
54 -- * Mathematical functions
56 -- Simple and slow statistical functions, please replace with better versions
58 -- | Mean value of a list.
59 meanValue :: Floating a => [a] -> a
60 meanValue lst = (sum lst) / (fromIntegral $ length lst)
62 -- | Standard deviation.
63 stdDev :: Floating a => [a] -> a
65 let mv = meanValue lst
66 square = (^ (2::Int)) -- silences "defaulting the constraint..."
67 av = sum $ map square $ map (\e -> e - mv) lst
68 bv = sqrt (av / (fromIntegral $ length lst))
71 -- | Coefficient of variation.
72 varianceCoeff :: Floating a => [a] -> a
73 varianceCoeff lst = (stdDev lst) / (fromIntegral $ length lst)
75 -- * JSON-related functions
77 -- | Converts a JSON Result into a monadic value.
78 fromJResult :: Monad m => J.Result a -> m a
79 fromJResult (J.Error x) = fail x
80 fromJResult (J.Ok x) = return x
82 -- | Tries to read a string from a JSON value.
84 -- In case the value was not a string, we fail the read (in the
85 -- context of the current monad.
86 readEitherString :: (Monad m) => J.JSValue -> m String
89 J.JSString s -> return $ J.fromJSString s
90 _ -> fail "Wrong JSON type"
92 -- | Converts a JSON message into an array of JSON objects.
93 loadJSArray :: (Monad m) => String -> m [J.JSObject J.JSValue]
94 loadJSArray s = fromJResult $ J.decodeStrict s
96 -- | Reads a the value of a key in a JSON object.
97 fromObj :: (J.JSON a, Monad m) => String -> J.JSObject J.JSValue -> m a
99 case lookup k (J.fromJSObject o) of
100 Nothing -> fail $ printf "key '%s' not found in %s" k (show o)
101 Just val -> fromJResult $ J.readJSON val
103 -- | Converts a JSON value into a JSON object.
104 asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
105 asJSObject (J.JSObject a) = return a
106 asJSObject _ = fail "not an object"
108 -- | Coneverts a list of JSON values into a list of JSON objects.
109 asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
110 asObjectList = sequence . map asJSObject