If a key has no value, it returns a supplied monadic default value.

Signed-off-by: Petr Pudlak <[email protected]>
---
 src/Ganeti/JSON.hs | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/src/Ganeti/JSON.hs b/src/Ganeti/JSON.hs
index 80bec06..a9f6f1e 100644
--- a/src/Ganeti/JSON.hs
+++ b/src/Ganeti/JSON.hs
@@ -48,6 +48,7 @@ module Ganeti.JSON
   , toArray
   , optionalJSField
   , optFieldsToObj
+  , lookupContainer
   , readContainer
   , DictObject(..)
   , ArrayObject(..)
@@ -313,6 +314,14 @@ instance F.Traversable (GenericContainer a) where
 -- | Type alias for string keys.
 type Container = GenericContainer String
 
+-- | Looks up a value in a container with a default value.
+-- If a key has no value, a given monadic default is returned.
+-- This allows simple error handling, as the default can be
+-- 'mzero', 'failError' etc.
+lookupContainer :: (Monad m, Ord a)
+                => m b -> a -> GenericContainer a b -> m b
+lookupContainer dflt k = maybe dflt return . Map.lookup k . fromContainer
+
 -- | Container loader.
 readContainer :: (Monad m, HasStringRepr a, Ord a, J.JSON b) =>
                  J.JSObject J.JSValue -> m (GenericContainer a b)
-- 
1.9.1.423.g4596e3a

Reply via email to