aboutsummaryrefslogtreecommitdiff
path: root/src/Common.hs
diff options
context:
space:
mode:
authorevuez <julien@mulga.net>2024-04-01 15:17:30 +0200
committerevuez <julien@mulga.net>2024-04-03 22:45:36 +0200
commit985974c264804ff788b3b5242fef707d4b7fa9a6 (patch)
treed80f83db178c3fd1b83b3b749793d47236dde35d /src/Common.hs
downloadwebmaild-985974c264804ff788b3b5242fef707d4b7fa9a6.tar.gz
Initial commit
Diffstat (limited to 'src/Common.hs')
-rw-r--r--src/Common.hs82
1 files changed, 82 insertions, 0 deletions
diff --git a/src/Common.hs b/src/Common.hs
new file mode 100644
index 0000000..91bf708
--- /dev/null
+++ b/src/Common.hs
@@ -0,0 +1,82 @@
+module Common
+ ( toLower
+ , trim
+ , trimWith
+ , splitOn
+ , split2
+ , replace
+ , (!!?)
+ , findVal
+ , maybeAt
+ , startsWith
+ , delete
+ )
+where
+
+import Data.Char (isSpace)
+import qualified Data.Char as C
+import Data.List (find, stripPrefix)
+import Intro
+
+trim :: String -> String
+trim = f . f
+ where
+ f = reverse . dropWhile isSpace
+
+trimWith :: (Char -> Bool) -> String -> String
+trimWith p = f . f
+ where
+ f = reverse . dropWhile p
+
+splitOn :: (a -> Bool) -> [a] -> [[a]]
+splitOn p s = case dropWhile p s of
+ [] -> []
+ s' -> w : splitOn p s''
+ where
+ (w, s'') = break p s'
+
+split2 :: (a -> Bool) -> [a] -> ([a], [a])
+split2 p s =
+ case break p s of
+ (x, _ : y) -> (x, y)
+ (x, []) -> (x, [])
+
+infix 9 !!?
+
+(!!?) :: [a] -> Int -> Maybe a
+(!!?) xs i
+ | i < 0 = Nothing
+ | otherwise = go i xs
+ where
+ go :: Int -> [a] -> Maybe a
+ go 0 (x : _) = Just x
+ go j (_ : ys) = go (j - 1) ys
+ go _ [] = Nothing
+
+maybeAt :: Int -> [a] -> Maybe a
+maybeAt = flip (!!?)
+
+toLower :: String -> String
+toLower = fmap C.toLower
+
+startsWith :: (a -> Bool) -> [a] -> Bool
+startsWith _ [] = False
+startsWith p (x : _) = p x
+
+findVal :: (a -> Bool) -> [(a, b)] -> Maybe b
+findVal p xs = snd <$> find (p . fst) xs
+
+replace :: (Eq a) => [a] -> [a] -> [a] -> [a]
+replace [] to xs = go xs
+ where
+ go [] = to
+ go (x : xs') = to ++ x : go xs'
+replace from to xs | Just xs' <- stripPrefix from xs = to ++ replace from to xs'
+replace from to (x : xs) = x : replace from to xs
+replace _ _ [] = []
+
+delete :: (a -> Bool) -> [a] -> (Maybe a, [a])
+delete p = foldr f (Nothing, [])
+ where
+ f x (Nothing, xs) | p x = (Just x, xs)
+ f x (m, xs) = (m, x : xs)