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)