unique elements in a haskell list
Solution 1
The nub
function from Data.List
(no, it's actually not in the Prelude) definitely does something like what you want, but it is not quite the same as your unique
function. They both preserve the original order of the elements, but unique
retains the last
occurrence of each element, while nub
retains the first occurrence.
You can do this to make nub
act exactly like unique
, if that's important (though I have a feeling it's not):
unique = reverse . nub . reverse
Also, nub
is only good for small lists.
Its complexity is quadratic, so it starts to get slow if your list can contain hundreds of elements.
If you limit your types to types having an Ord instance, you can make it scale better.
This variation on nub
still preserves the order of the list elements, but its complexity is O(n * log n)
:
import qualified Data.Set as Set
nubOrd :: Ord a => [a] -> [a]
nubOrd xs = go Set.empty xs where
go s (x:xs)
| x `Set.member` s = go s xs
| otherwise = x : go (Set.insert x s) xs
go _ _ = []
In fact, it has been proposed to add nubOrd
to Data.Set
.
Solution 2
I searched for (Eq a) => [a] -> [a]
on Hoogle.
First result was nub
(remove duplicate elements from a list).
Hoogle is awesome.
Solution 3
import Data.Set (toList, fromList)
uniquify lst = toList $ fromList lst
Solution 4
I think that unique should return a list of elements that only appear once in the original list; that is, any elements of the orginal list that appear more than once should not be included in the result.
May I suggest an alternative definition, unique_alt:
unique_alt :: [Int] -> [Int]
unique_alt [] = []
unique_alt (x:xs)
| elem x ( unique_alt xs ) = [ y | y <- ( unique_alt xs ), y /= x ]
| otherwise = x : ( unique_alt xs )
Here are some examples that highlight the differences between unique_alt and unqiue:
unique [1,2,1] = [2,1]
unique_alt [1,2,1] = [2]
unique [1,2,1,2] = [1,2]
unique_alt [1,2,1,2] = []
unique [4,2,1,3,2,3] = [4,1,2,3]
unique_alt [4,2,1,3,2,3] = [4,1]
Solution 5
I think this would do it.
unique [] = []
unique (x:xs) = x:unique (filter ((/=) x) xs)

muhmuhten
Updated on February 12, 2022Comments
-
muhmuhten 10 months
okay, this is probably going to be in the prelude, but: is there a standard library function for finding the unique elements in a list? my (re)implementation, for clarification, is:
has :: (Eq a) => [a] -> a -> Bool has [] _ = False has (x:xs) a | x == a = True | otherwise = has xs a unique :: (Eq a) => [a] -> [a] unique [] = [] unique (x:xs) | has xs x = unique xs | otherwise = x : unique xs