[gitconv @ N.M.Commands.hs: add parser helper for building structures]
[libmpd-haskell.git] / Network / MPD / Utils.hs
blob040eceed0c3d67d558b1062f84146731d1f40f3f
1 {-
2 libmpd for Haskell, an MPD client library.
3 Copyright (C) 2005-2008 Ben Sinclair <bsinclai@turing.une.edu.au>
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 -- | Module : Network.MPD.Utils
21 -- Copyright : (c) Ben Sinclair 2005-2008
22 -- License : LGPL
23 -- Maintainer : bsinclai@turing.une.edu.au
24 -- Stability : alpha
25 -- Portability : Haskell 98
27 -- Utilities.
29 module Network.MPD.Utils (
30 parseNum, parseBool, showBool,
31 toAssoc, splitGroups
32 ) where
34 -- Parse a positive or negative integer value, returning 'Nothing' on failure.
35 parseNum :: (Read a, Integral a) => String -> Maybe a
36 parseNum s = do
37 [(x, "")] <- return (reads s)
38 return x
40 -- Inverts 'parseBool'.
41 showBool :: Bool -> String
42 showBool x = if x then "1" else "0"
44 -- Parse a boolean response value.
45 parseBool :: String -> Bool
46 parseBool = (== "1") . take 1
48 -- Break up a list of strings into an assoc. list, separating at
49 -- the first ':'.
50 toAssoc :: [String] -> [(String, String)]
51 toAssoc = map f
52 where f x = let (k,v) = break (== ':') x in
53 (k,dropWhile (== ' ') $ drop 1 v)
55 -- Takes an assoc. list with recurring keys, and groups each cycle of
56 -- keys with their values together. The first key of each cycle needs
57 -- to be present in every cycle for it to work, but the rest don't
58 -- affect anything.
60 -- > splitGroups [(1,'a'),(2,'b'),(1,'c'),(2,'d')] ==
61 -- > [[(1,'a'),(2,'b')],[(1,'c'),(2,'d')]]
62 splitGroups :: Eq a => [(a, b)] -> [[(a, b)]]
63 splitGroups [] = []
64 splitGroups (x:xs) = ((x:us):splitGroups vs)
65 where (us,vs) = break (\y -> fst x == fst y) xs