2020-02-13 20:38:23 +03:00
|
|
|
module Data.List.Extended
|
2021-09-24 01:56:37 +03:00
|
|
|
( duplicates,
|
|
|
|
uniques,
|
|
|
|
getDifference,
|
|
|
|
getDifferenceOn,
|
|
|
|
getOverlapWith,
|
2022-02-25 23:37:32 +03:00
|
|
|
longestCommonPrefix,
|
2022-03-07 13:11:58 +03:00
|
|
|
appendToNonEmpty,
|
2021-09-24 01:56:37 +03:00
|
|
|
module L,
|
|
|
|
)
|
|
|
|
where
|
|
|
|
|
|
|
|
import Data.Function (on)
|
|
|
|
import Data.HashMap.Strict.Extended qualified as Map
|
|
|
|
import Data.HashSet qualified as Set
|
|
|
|
import Data.Hashable (Hashable)
|
|
|
|
import Data.List qualified as L
|
|
|
|
import Data.List.NonEmpty qualified as NE
|
2022-03-08 16:02:13 +03:00
|
|
|
import Data.Set qualified as S
|
2021-09-24 01:56:37 +03:00
|
|
|
import Prelude
|
2020-02-13 20:38:23 +03:00
|
|
|
|
|
|
|
duplicates :: (Eq a, Hashable a) => [a] -> Set.HashSet a
|
|
|
|
duplicates =
|
2021-09-24 01:56:37 +03:00
|
|
|
Set.fromList . Map.keys . Map.filter (> 1) . Map.fromListWith (+) . map (,1 :: Int)
|
2020-05-27 18:02:58 +03:00
|
|
|
|
2022-03-08 16:02:13 +03:00
|
|
|
uniques :: (Ord a) => [a] -> [a]
|
|
|
|
uniques = S.toList . S.fromList
|
2020-12-21 12:11:37 +03:00
|
|
|
|
|
|
|
getDifference :: (Eq a, Hashable a) => [a] -> [a] -> Set.HashSet a
|
|
|
|
getDifference = Set.difference `on` Set.fromList
|
2021-05-27 18:06:13 +03:00
|
|
|
|
|
|
|
getDifferenceOn :: (Eq k, Hashable k) => (v -> k) -> [v] -> [v] -> [v]
|
|
|
|
getDifferenceOn f l = Map.elems . Map.differenceOn f l
|
|
|
|
|
|
|
|
getOverlapWith :: (Eq k, Hashable k) => (v -> k) -> [v] -> [v] -> [(v, v)]
|
|
|
|
getOverlapWith getKey left right =
|
|
|
|
Map.elems $ Map.intersectionWith (,) (mkMap left) (mkMap right)
|
|
|
|
where
|
|
|
|
mkMap = Map.fromList . map (\v -> (getKey v, v))
|
2021-07-30 14:33:06 +03:00
|
|
|
|
2022-02-25 23:37:32 +03:00
|
|
|
-- | Returns the longest prefix common to all given lists. Returns an empty list on an empty list.
|
|
|
|
--
|
|
|
|
-- >>> longestCommonPrefix ["abcd", "abce", "abgh"]
|
|
|
|
-- "ab"
|
|
|
|
--
|
|
|
|
-- >>> longestCommonPrefix []
|
|
|
|
-- []
|
|
|
|
longestCommonPrefix :: Eq a => [[a]] -> [a]
|
|
|
|
longestCommonPrefix [] = []
|
|
|
|
longestCommonPrefix (x : xs) = foldr prefix x xs
|
|
|
|
where
|
|
|
|
prefix l1 l2 = map fst $ takeWhile (uncurry (==)) $ zip l1 l2
|
2022-03-07 13:11:58 +03:00
|
|
|
|
|
|
|
appendToNonEmpty :: NE.NonEmpty a -> [a] -> NE.NonEmpty a
|
|
|
|
appendToNonEmpty (neHead NE.:| neList) list =
|
|
|
|
neHead NE.:| (neList <> list)
|