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,
|
|
|
|
hasNoDuplicates,
|
2022-02-25 23:37:32 +03:00
|
|
|
longestCommonPrefix,
|
2022-03-07 13:11:58 +03:00
|
|
|
appendToNonEmpty,
|
2022-03-08 11:22:20 +03:00
|
|
|
singleton,
|
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
|
|
|
|
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
|
|
|
|
|
|
|
uniques :: Eq a => [a] -> [a]
|
|
|
|
uniques = map NE.head . NE.group
|
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
|
|
|
|
|
|
|
hasNoDuplicates :: (Eq a, Hashable a) => [a] -> Bool
|
|
|
|
hasNoDuplicates xs = Set.size (Set.fromList xs) == length xs
|
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)
|
2022-03-08 11:22:20 +03:00
|
|
|
|
|
|
|
-- | As of base-4.15.0.0 (GHC > 9) singleton now exists in Data.List so we should be able to remove this when we upgrade.
|
|
|
|
singleton :: a -> [a]
|
|
|
|
singleton = pure
|