@@ -1,5 +1,5 @@
1+--------------------------------------------------------------------------------
12-- | Miscellaneous string manipulation functions.
2−--
33module Hakyll.Core.Util.String
44 ( trim
55 , replaceAll
@@ -7,21 +7,24 @@ module Hakyll.Core.Util.String
77 , needlePrefix
88 ) where
99
10+
11+--------------------------------------------------------------------------------
1012import Data.Char (isSpace)
1113import Data.List (isPrefixOf)
1214import Data.Maybe (listToMaybe)
13−
1415import Text.Regex.TDFA ((=~~))
1516
17+
18+--------------------------------------------------------------------------------
1619-- | Trim a string (drop spaces, tabs and newlines at both sides).
17−--
1820trim :: String -> String
1921trim = reverse . trim' . reverse . trim'
2022 where
2123 trim' = dropWhile isSpace
2224
25+
26+--------------------------------------------------------------------------------
2327-- | A simple (but inefficient) regex replace funcion
24−--
2528replaceAll :: String -- ^ Pattern
2629 -> (String -> String) -- ^ Replacement (called on capture)
2730 -> String -- ^ Source string
@@ -35,9 +38,10 @@ replaceAll pattern f source = replaceAll' source
3538 (capture, after) = splitAt l tmp
3639 in before ++ f capture ++ replaceAll' after
3740
41+
42+--------------------------------------------------------------------------------
3843-- | A simple regex split function. The resulting list will contain no empty
3944-- strings.
40−--
4145splitAll :: String -- ^ Pattern
4246 -> String -- ^ String to split
4347 -> [String] -- ^ Result
@@ -50,19 +54,24 @@ splitAll pattern = filter (not . null) . splitAll'
5054 in before : splitAll' (drop l tmp)
5155
5256
53−-- | Find the first instance of needle (must be non-empty) in
54−-- haystack. We return the prefix of haystack before needle is
55−-- matched.
57+
58+--------------------------------------------------------------------------------
59+-- | Find the first instance of needle (must be non-empty) in haystack. We
60+-- return the prefix of haystack before needle is matched.
5661--
5762-- Examples:
58−-- needlePrefix "cd" "abcde" = "ab"
59−-- needlePrefix "ab" "abc" = ""
60−-- needlePrefix "ab" "xxab" = "xx"
61−-- needlePrefix "a" "xx" = "xx"
6263--
63−needlePrefix :: String -> String -> String
64−needlePrefix needle haystack = go haystack
64+-- > needlePrefix "cd" "abcde" = "ab"
65+--
66+-- > needlePrefix "ab" "abc" = ""
67+--
68+-- > needlePrefix "ab" "xxab" = "xx"
69+--
70+-- > needlePrefix "a" "xx" = "xx"
71+needlePrefix :: String -> String -> Maybe String
72+needlePrefix needle haystack = go [] haystack
6573 where
66− go [] = []
67− go xss@(x:xs) | needle `isPrefixOf` xss = []
68− | otherwise = x : go xs
74+ go _ [] = Nothing
75+ go acc xss@(x:xs)
76+ | needle `isPrefixOf` xss = Just $ reverse acc
77+ | otherwise = go (x : acc) xs