From 985974c264804ff788b3b5242fef707d4b7fa9a6 Mon Sep 17 00:00:00 2001 From: evuez Date: Mon, 1 Apr 2024 15:17:30 +0200 Subject: Initial commit --- src/Common.hs | 82 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 src/Common.hs (limited to 'src/Common.hs') 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) -- cgit v1.2.3