summaryrefslogtreecommitdiff
path: root/src/Hakyll/Core
diff options
context:
space:
mode:
Diffstat (limited to 'src/Hakyll/Core')
-rw-r--r--src/Hakyll/Core/Util/String.hs43
1 files changed, 26 insertions, 17 deletions
diff --git a/src/Hakyll/Core/Util/String.hs b/src/Hakyll/Core/Util/String.hs
index d9ec91c..b46f7b8 100644
--- a/src/Hakyll/Core/Util/String.hs
+++ b/src/Hakyll/Core/Util/String.hs
@@ -1,5 +1,5 @@
+--------------------------------------------------------------------------------
-- | Miscellaneous string manipulation functions.
---
module Hakyll.Core.Util.String
( trim
, replaceAll
@@ -7,21 +7,24 @@ module Hakyll.Core.Util.String
, needlePrefix
) where
+
+--------------------------------------------------------------------------------
import Data.Char (isSpace)
import Data.List (isPrefixOf)
import Data.Maybe (listToMaybe)
-
import Text.Regex.TDFA ((=~~))
+
+--------------------------------------------------------------------------------
-- | Trim a string (drop spaces, tabs and newlines at both sides).
---
trim :: String -> String
trim = reverse . trim' . reverse . trim'
where
trim' = dropWhile isSpace
+
+--------------------------------------------------------------------------------
-- | A simple (but inefficient) regex replace funcion
---
replaceAll :: String -- ^ Pattern
-> (String -> String) -- ^ Replacement (called on capture)
-> String -- ^ Source string
@@ -35,9 +38,10 @@ replaceAll pattern f source = replaceAll' source
(capture, after) = splitAt l tmp
in before ++ f capture ++ replaceAll' after
+
+--------------------------------------------------------------------------------
-- | A simple regex split function. The resulting list will contain no empty
-- strings.
---
splitAll :: String -- ^ Pattern
-> String -- ^ String to split
-> [String] -- ^ Result
@@ -50,19 +54,24 @@ splitAll pattern = filter (not . null) . splitAll'
in before : splitAll' (drop l tmp)
--- | Find the first instance of needle (must be non-empty) in
--- haystack. We return the prefix of haystack before needle is
--- matched.
+
+--------------------------------------------------------------------------------
+-- | Find the first instance of needle (must be non-empty) in haystack. We
+-- return the prefix of haystack before needle is matched.
--
-- Examples:
--- needlePrefix "cd" "abcde" = "ab"
--- needlePrefix "ab" "abc" = ""
--- needlePrefix "ab" "xxab" = "xx"
--- needlePrefix "a" "xx" = "xx"
--
-needlePrefix :: String -> String -> String
-needlePrefix needle haystack = go haystack
+-- > needlePrefix "cd" "abcde" = "ab"
+--
+-- > needlePrefix "ab" "abc" = ""
+--
+-- > needlePrefix "ab" "xxab" = "xx"
+--
+-- > needlePrefix "a" "xx" = "xx"
+needlePrefix :: String -> String -> Maybe String
+needlePrefix needle haystack = go [] haystack
where
- go [] = []
- go xss@(x:xs) | needle `isPrefixOf` xss = []
- | otherwise = x : go xs
+ go _ [] = Nothing
+ go acc xss@(x:xs)
+ | needle `isPrefixOf` xss = Just $ reverse acc
+ | otherwise = go (x : acc) xs