查找2个元素重复的列表

时间:2012-03-07 19:41:27

标签: list haskell

我正在寻找一个相对有效的功能来解决以下问题:

鉴于records :: [[String]],我想查找并返回其第一个第二个元素相同的所有[String]。所以给出:

records = [["Z", "Jay", "$500M"],
           ["Dilla", "J", "$0"],
           ["Z", "Jay", "$600M"], -- Note the different third element
           ["McCartney", "Paul", "like $1B"],
           ["McCartney", "Paul", "like $1B"],
           ["McCartney", "Joe", "$10"]]

dupFind records应该返回

[["Z", "Jay", "$500M"],
 ["Z", "Jay", "$600M"],
 ["McCartney", "Paul", "like $5B"],
 ["McCartney", "Paul", "like $5B"]]

我在使用sort-then-iterate查找重复项的典型方法时遇到问题,因为即使列表按其第一个元素排序,其重复记录也可能不相邻。

1 个答案:

答案 0 :(得分:4)

为什么不按前两个元素对列表进行排序?

import Data.List(sortBy)
import Data.Ord(comparing)

sortBy (comparing (take 2))

应该做的。