1
2-- | Operations on lists, generated to an arbitrary generating equality
3module System.FilePattern.ListBy(
4    eqListBy, stripPrefixBy, stripSuffixBy, stripInfixBy
5    ) where
6
7import Control.Applicative
8import Data.Tuple.Extra
9
10
11eqListBy :: (a -> b -> Maybe c) -> [a] -> [b] -> Maybe [c]
12eqListBy _ [] [] = Just []
13eqListBy eq (a:as) (b:bs) = liftA2 (:) (eq a b) (eqListBy eq as bs)
14eqListBy _ _ _ = Nothing
15
16
17stripPrefixBy :: (a -> b -> Maybe c) -> [a] -> [b] -> Maybe ([c], [b])
18stripPrefixBy eq [] bs = Just ([], bs)
19stripPrefixBy eq _  [] = Nothing
20stripPrefixBy eq (a:as) (b:bs) = do c <- eq a b; first (c:) <$> stripPrefixBy eq as bs
21
22stripSuffixBy :: (a -> b -> Maybe c) -> [a] -> [b] -> Maybe ([b], [c])
23stripSuffixBy eq [] bs = Just (bs, []) -- shortcut, but equal to the equation below
24stripSuffixBy eq _  [] = Nothing       -- shortcut, but equal to the equation below
25stripSuffixBy eq as bs = (\(c,b) -> (reverse b, reverse c)) <$> stripPrefixBy eq (reverse as) (reverse bs)
26
27stripInfixBy :: (a -> b -> Maybe c) -> [a] -> [b] -> Maybe ([b], [c], [b])
28stripInfixBy eq needle haystack | Just (ans, rest) <- stripPrefixBy eq needle haystack = Just ([], ans, rest)
29stripInfixBy eq needle [] = Nothing
30stripInfixBy eq needle (x:xs) = (\(a,b,c) -> (x:a,b,c)) <$> stripInfixBy eq needle xs
31