问题
I try to remove the Integer duplicates of a List of (String, Int)
, where I am guaranteed that there is no String
duplicate.
Is it possible to evaluate something like this in Haskell:
I tried:
[(a,b) | (a,b) <- bs, (c,k) <- bs, ((k == b) <= (a == c))]
but this does not yet work.
Edit: I am well aware, that you can achieve that using more complex syntax. For example by recursively searching the List for each elements duplicates...
回答1:
(NB: this is a completely new version of this answer. Previous was totally off-base.)
To follow your mathematical set comprehension more closely, we can tweak the definition in your answer as
uniquesOnly :: (Eq a, Eq b) => [(a, b)] -> [(a, b)]
uniquesOnly bs =
[(a,b) | (a,b) <- bs,
[(c,d) | (c,d) <- bs, d == b] ==
[(a,d) | (c,d) <- bs, d == b]]
"for all (c,d) in bs such that d==b it follows c==a".
uniquesOnly [(1,1),(2,2),(3,1)]
returns [(2,2)]
.
回答2:
This is a possible solution:
For example, I have made up this equivalent statement:
removeDuplicates :: [(String, Int)] -> [(String, Int)]
removeDuplicates bs =
[(a,b) | (a,b) <- bs,
length [(c,d) | (c,d) <- bs, d == b] == 1]
But this is not the same statement only an equal one.
回答3:
The existing answers don't take advantage of the guarantee that the strings are unique or the fact that Int
is ordered. Here's one that does.
import Data.List (sortBy, groupBy)
import Data.Function (on)
uniquesOnly :: Ord b => [(a, b)] -> [(a, b)]
uniquesOnly ps
= [ p
| [p] <- groupBy ((==) `on` snd) .
sortBy (compare `on` snd) $ ps ]
来源:https://stackoverflow.com/questions/64942087/checking-for-all-elements-in-a-set-in-haskell-using-syntactic-sugar