|
| 1 | +{-# LANGUAGE CPP #-} |
| 2 | +#if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703 |
| 3 | +{-# LANGUAGE Safe #-} |
| 4 | +#endif |
| 5 | + |
| 6 | +----------------------------------------------------------------------------- |
| 7 | +-- | |
| 8 | +-- Module : Data.Containers.ListUtils |
| 9 | +-- Copyright : (c) Gershom Bazerman 2018 |
| 10 | +-- License : BSD-style |
| 11 | + |
| 12 | +-- Portability : portable |
| 13 | +-- |
| 14 | +-- This module provides efficient containers-based functions on the list type. |
| 15 | +----------------------------------------------------------------------------- |
| 16 | + |
| 17 | +module Data.Containers.ListUtils ( |
| 18 | + nubOrd, |
| 19 | + nubOrdOn, |
| 20 | + nubInt, |
| 21 | + nubIntOn |
| 22 | + ) where |
| 23 | + |
| 24 | +import qualified Data.Set as Set |
| 25 | +import qualified Data.IntSet as IntSet |
| 26 | + |
| 27 | +-- | /O(n log n)/. The 'nubOrd' function removes duplicate elements from a list. |
| 28 | +-- In particular, it keeps only the first occurrence of each element. By using a 'Set' internally |
| 29 | +-- it has better asymptotics than the standard 'nub' function. |
| 30 | +nubOrd :: (Ord a) => [a] -> [a] |
| 31 | +nubOrd = go Set.empty |
| 32 | + where |
| 33 | + go _ [] = [] |
| 34 | + go s (x:xs) = if x `Set.member` s then go s xs |
| 35 | + else x : go (Set.insert x s) xs |
| 36 | + |
| 37 | +-- | The `nubOrdOn` function behaves just like `nubOrd` except it performs comparisons not on the |
| 38 | +-- original datatype, but a user-specified projection from that datatype. |
| 39 | +nubOrdOn :: (Ord b) => (a -> b) -> [a] -> [a] |
| 40 | +nubOrdOn f = go Set.empty |
| 41 | + where |
| 42 | + go _ [] = [] |
| 43 | + go s (x:xs) = let fx = f x |
| 44 | + in if fx `Set.member` s then go s xs |
| 45 | + else x : go (Set.insert fx s) xs |
| 46 | + |
| 47 | +-- | /O(n min(n,W))/. The 'nubInt' function removes duplicate elements from a list. |
| 48 | +-- In particular, it keeps only the first occurrence of each element. By using an 'IntSet' internally |
| 49 | +-- it has better asymptotics than the standard 'nub' function. |
| 50 | +nubInt :: [Int] -> [Int] |
| 51 | +nubInt = go IntSet.empty |
| 52 | + where |
| 53 | + go _ [] = [] |
| 54 | + go s (x:xs) = if x `IntSet.member` s then go s xs |
| 55 | + else x : go (IntSet.insert x s) xs |
| 56 | + |
| 57 | +-- | The `nubIntOn` function behaves just like 'nubInt' except it performs comparisons not on the |
| 58 | +-- original datatype, but a user-specified projection from that datatype to 'Int'. |
| 59 | +nubIntOn :: (a -> Int) -> [a] -> [a] |
| 60 | +nubIntOn f = go IntSet.empty |
| 61 | + where |
| 62 | + go _ [] = [] |
| 63 | + go s (x:xs) = let fx = f x |
| 64 | + in if fx `IntSet.member` s then go s xs |
| 65 | + else x : go (IntSet.insert fx s) xs |
0 commit comments