From 36bf3424e0e231142365dac7ec6f56c8ef038820 Mon Sep 17 00:00:00 2001 From: Ben Sinclair Date: Sat, 5 Apr 2008 14:21:00 +0000 Subject: [PATCH] wibble: forgot to add N.M.Parse... darcs-hash:20080405142135-87dc9-047cf4196ca0c43fe8994cc415c10ca69a2f7a92.gz --- Network/MPD/Parse.hs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Network/MPD/Parse.hs diff --git a/Network/MPD/Parse.hs b/Network/MPD/Parse.hs new file mode 100644 index 0000000..2a14642 --- /dev/null +++ b/Network/MPD/Parse.hs @@ -0,0 +1,35 @@ +module Network.MPD.Parse where + +import Control.Monad.Error +import Network.MPD.Utils + +type Seconds = Integer + +-- | Represents the result of running 'count'. +data Count = + Count { cSongs :: Integer -- ^ Number of songs matching the query + , cPlaytime :: Seconds -- ^ Total play time of matching songs + } + deriving (Eq, Show) + +parseCount :: [String] -> Either String Count +parseCount = foldM f empty . toAssoc + where f a ("songs", x) = parse parseNum + (\x' -> a { cSongs = x'}) x + f a ("playtime", x) = parse parseNum + (\x' -> a { cPlaytime = x' }) x + f _ x = Left $ show x + empty = Count { cSongs = 0, cPlaytime = 0 } + +-- A helper that runs a parser on a string and, depending, on the +-- outcome, either returns the result of some command applied to the +-- result, or fails. Used when building structures. +parse :: Monad m => (String -> Maybe a) -> (a -> b) -> String -> m b +parse p g x = maybe (fail x) (return . g) (p x) + +-- A helper for running a parser returning Maybe on a pair of strings. +-- Returns Just if both strings where parsed successfully, Nothing otherwise. +pair :: (String -> Maybe a) -> (String, String) -> Maybe (a, a) +pair p (x, y) = case (p x, p y) of + (Just a, Just b) -> Just (a, b) + _ -> Nothing -- 2.11.4.GIT