---------------------------------------------------------
-- |
-- Module : Data.String.Util
-- Copyright : Michael Snoyman
-- License : BSD3
--
-- Maintainer : Michael Snoyman <michael@snoyman.com>
-- Stability : Unstable
-- Portability : portable
--
-- Various utilities to assist in dealing with Strings.
--
---------------------------------------------------------
module Data.String.Util
( chomp
, dropPrefix
, dropQuotes
, splitList
) where
import Data.List (isPrefixOf)
-- | Removes newline characters from the end of a string.
chomp :: String -> String
chomp s
| null s = s
| last s == '\n' =
if length s == 1 || last (init s) /= '\r'
then init s
else init (init s)
| last s == '\r' = init s
| otherwise = s
-- | Drop a string from the beginning of another, if present.
dropPrefix :: Eq a => [a] -> [a] -> [a]
dropPrefix x y
| x `isPrefixOf` y = drop (length x) y
| otherwise = y
-- | Drop surrounding quotes, if present.
dropQuotes :: String -> String
dropQuotes s
| length s > 2 && head s == '"' && last s == '"' = tail $ init s
| otherwise = s
-- | Split up a list into sublists at every occurence of the split
-- element. That element is thrown away.
splitList :: Eq a => a -> [a] -> [[a]]
splitList c s = helper s [[]] where
helper [] res = filter (not . null) $ reverse $ map reverse res
helper (x:xs) (y:ys)
| x == c = helper xs ([]:y:ys)
| otherwise = helper xs ((x:y):ys)
helper _ [] = error "This case should never be"