Reputation: 367
I want to write a function that takes as argument a list of tuples like this:
remove' [ ("a", True), ("b", False), ("c", False), ("d", True) ]
I would like to return a list of tuples that have False as their second value, so I'd like my function to return
[ ("b", False), ("c", False) ]
Here's what I have so far but it won't load in GHCi. can anyone help me out? Thanks
remove' :: [(a,b)] -> [(a,b)]
remove' [(a,b)] = [ c | c <- [(a,b)], c `notElem` True ]
Upvotes: 1
Views: 3708
Reputation: 239473
Since you want to match the second element of the tuples, you need to pick the second element from the tuple and compare it with False
like this
remove' :: [(a, Bool)] -> [(a, Bool)]
remove' xs = [c | c <- xs, snd c == False]
The snd
function will get second element from each of the tuples and compare them with False
. Only if they match, they will be gathered in the resulting list.
Since the second elements are booleans, you can make use of the not
function like this
[c | c <- xs, (not . snd) c]
We can express the same wihtout the dot notation like this
[c | c <- xs, not(snd(c))]
Note: In your program, you have
remove' [(a,b)] = ...
it means that, it will be executed only when remove is called with a list of tuples of size 1
. You can check that like this
remove' :: [(a, Bool)] -> [(a, Bool)]
remove' [(a, b)] = [(a, b)]
remove' [ ("a", True), ("b", False), ("c", False), ("d", True) ]
will print
Non-exhaustive patterns in function remove'
It means the patterns you specified in the function definition is not covering all the possible inputs. Since we need process a list of tuples of any length, we accept it in xs
and use it in the List Comprehension.
Upvotes: 4
Reputation: 445
You just need filter and select second item in lambda:
filter (\x -> (snd x) == False) [("a", False), ("b", True)]
Response:
[("a",False)]
Upvotes: 0