Giving a list of pairs, for example
[(1, 2), (1, 3), (1, 4), (2, 1), (3, 1), (4, 1)]
So, I am trying to remove the pair duplicates, I consider a pair to be duplicate if (x, y) == (y, x), for example: (1, 2) with (3, 1)
I am generating the list with a comprehension list, it is derived from one single list
MyList = [(intA, intB) | x <- integerList, y <- integerList, x /= y]
integerList = [1, 2, 3];
Please note that the first thing I wrote is just an example of what I want to happen and it is not the output of the comprehension list above.
I recently started using Haskell, how would I approach the problem? What would be the best choice? I tried using map, but without success, should I combine a map with a foldl / foldr that uses reverse inside it? How would I do that?
This is a perfect time to use Hoogle! Let's think about what you're looking for. To remove duplicates, we want something that takes a list [a] and removes things from it, returning [a] based on some predicate a -> a -> Bool. This means we're looking for a function with the following form:
ourFunction :: (a -> a -> Bool) -> [a] -> [a]
We can actually search Hoogle using the function signature, (a -> a -> Bool) -> [a] -> [a], and the first result is nubBy, which does exactly what we want!
That being said, you don't need to use this to fix your problem. You're already on the right track. Think about what you're asking -- you want no duplicate tuples where (x, y) == (y, x). So just choose whether or not you want y < x or the other way around, and use this in your list comprehension:
> let fn xs = [(a, b) | a <- xs, b <- xs, a < b]
> fn [1, 2, 3]
[(1,2),(1,3),(2,3)]
If you need both lists (one with duplicates and one without) I'd suggest using two separate list comprehensions. It is less performant, as the list comprehension as you have it written is O(n^2), but it's much cleaner and easier to learn from, in my opinion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With