mahjong
mahjong

Reputation: 13

Haskell : Filter list for elements of second list

I am currently trying to filter a list , that consist of tuples of the form (String , Double), for a List that consists of Strings. If the tuple doesn't contain a String of the second list, it should be removed from the list of tuples. So far I came up with this:

test :: [ExamScore] -> String -> [ExamScore]
test a b = filter ((== b).fst) a

My current problem is to replace the String that is filtered for by a list of Strings. Thanks for your help! Please go easy on me, I'm a first year informatics student that hasn't coded anytime before.

Upvotes: 0

Views: 293

Answers (1)

bereal
bereal

Reputation: 34282

It's almost the same, just another filter function using elem:

test a b :: [ExamScore] -> [String] -> [ExamScore]
test a b = filter (\(s, _) -> elem s b) a

Or, if you're more into the composition style:

test a b = filter (flip elem b . fst) a

(It's worth noting that it's not the most efficient way, since elem is O(N) for lists, so depending on your case you may want to find a better structure for storing the keys.)

Upvotes: 0

Related Questions