Checking for all Elements in a Set in Haskell using syntactic sugar

白昼怎懂夜的黑 提交于 2020-12-13 05:48:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!