amindfv
amindfv

Reputation: 8448

Find lists where 2 elements are duplicates

I'm looking for a relatively efficient function to solve the following problem:

Given records :: [[String]], I want to find and return all [String]s whose first and second elements are the same. So given:

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 should return

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

I'm having trouble with the typical method of sort-then-iterate for finding duplicates, because even when the list is sorted by its first element, its duplicate records may not be adjacent.

Upvotes: 0

Views: 393

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198014

Why not just sort the list by its first two elements?

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

sortBy (comparing (take 2))

should do the job.

Upvotes: 4

Related Questions