Haskell problem
I'm stuck on this exercise. Any help would be appreciated! Thanks in advance!
A function takeS takes a list of pairs and compares firs开发者_StackOverflowt elements of pairs. If they are not equal, the function returns that list of pairs. If they are equal, that means they have a conflict. The function will delete either one of these two pairs and returns the list with no conflict pairs. If the returning list still has some conflict pairs, the function recursively calls itself until there are no conflict pairs.
takeS :: [(a,b)] -> [(a,b)]
Example: takeS [("a",1),("b",2),("b",3),("c",4),("c",5)]
will return
[("a",1),("b",2),("c",4)]
since there are 2 conflict pairs: ("b",2)
, ("b",3)
and ("c",4)
, ("c",5)
.
import Data.List (nubBy)
takeS :: Eq a => [(a, b)] -> [(a, b)]
takeS = nubBy $ \(x, _) (y, _) -> x == y
If you don't want to import anything, you can define nubBy
yourself; here's one possible implementation (may be less efficient than the official version):
-- nubBy removes "duplicates" as defined by a binary predicate
nubBy :: (a -> a -> Bool) -> [a] -> [a]
nubBy f [] = []
nubBy f (x:xs) = x:(nubBy f (filter (not . f x) xs))
精彩评论