Search code examples
listhaskellfunctional-programming

Is there a function that takes a list and returns a list of duplicate elements in that list?


Is there a Haskell function that takes a list and returns a list of duplicates/redundant elements in that list?

I'm aware of the the nub and nubBy functions, but they remove the duplicates; I would like to keep the dupes and collects them in a list.


Solution

  • Is there a Haskell function that takes a list and returns a list of duplicates/redundant elements in that list?

    You can write such a function yourself easily enough. Use a helper function that takes two list arguments, the first one of which being the list whose dupes are sought; walk along that list and accumulate the dupes in the second argument; finally, return the latter when the first argument is the empty list.

    dupes l                                    = dupes' l []
      where
        dupes' []     ls                       = ls
        dupes' (x:xs) ls
            | not (x `elem` ls) && x `elem` xs = dupes' xs (x:ls)
            | otherwise                        = dupes' xs ls
    

    Test:

    λ> dupes [1,2,3,3,2,2,3,4]
    [3,2]
    

    Be aware that the asymptotic time complexity is as bad as that of nub, though: O(n^2). If you want better asymptotics, you'll need an Ord class constraint.