[gitconv @ Add and use 'breakChar']
[libmpd-haskell.git] / Network / MPD / Utils.hs
blobb68bf1c00fbed139a4a5bb13f3a5dbda733690d2
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 parseDate, parseNum, parseBool, showBool,
31 breakChar, toAssoc, splitGroups
32 ) where
34 import Data.Char (isDigit)
36 -- Break a string a character, removing the separator.
37 breakChar :: Char -> String -> (String, String)
38 breakChar c s = let (x, y) = break (== c) s in (x, drop 1 y)
40 -- XXX: need a more robust date parser.
41 -- Parse a date value.
42 -- > parseDate "2008" = Just 2008
43 -- > parseDate "2008-03-01" = Just 2008
44 parseDate :: String -> Maybe Int
45 parseDate = parseNum . takeWhile isDigit
47 -- Parse a positive or negative integer value, returning 'Nothing' on failure.
48 parseNum :: (Read a, Integral a) => String -> Maybe a
49 parseNum s = do
50 [(x, "")] <- return (reads s)
51 return x
53 -- Inverts 'parseBool'.
54 showBool :: Bool -> String
55 showBool x = if x then "1" else "0"
57 -- Parse a boolean response value.
58 parseBool :: String -> Maybe Bool
59 parseBool s = case take 1 s of
60 "1" -> Just True
61 "0" -> Just False
62 _ -> Nothing
64 -- Break up a list of strings into an assoc. list, separating at
65 -- the first ':'.
66 toAssoc :: [String] -> [(String, String)]
67 toAssoc = map f
68 where f x = let (k,v) = break (== ':') x in
69 (k,dropWhile (== ' ') $ drop 1 v)
71 -- Takes an assoc. list with recurring keys, and groups each cycle of
72 -- keys with their values together. The first key of each cycle needs
73 -- to be present in every cycle for it to work, but the rest don't
74 -- affect anything.
76 -- > splitGroups [(1,'a'),(2,'b'),(1,'c'),(2,'d')] ==
77 -- > [[(1,'a'),(2,'b')],[(1,'c'),(2,'d')]]
78 splitGroups :: Eq a => [(a, b)] -> [[(a, b)]]
79 splitGroups [] = []
80 splitGroups (x:xs) = ((x:us):splitGroups vs)
81 where (us,vs) = break (\y -> fst x == fst y) xs