Markeazy
Markeazy

Reputation: 76

How to find and/or delete an element in a List of tuples in Haskell

I have to write two functions: "find" and "delete". I need to use them to search through a List of tuples (pairs), and match the first element in each pair to a String. If the element matches the String, the "find" function should output the second element in the pair, and the "delete" function should delete that pair from the list.

I am unsure of how to recurse and search through a List in Haskell, how may I get started writing these functions?

Upvotes: 0

Views: 2447

Answers (1)

jkeuhlen
jkeuhlen

Reputation: 4517

Lists in Haskell have a few built in functions to make this easier. One way to do this, is to use the filter function:

find :: String -> [(String, a)] -> a
find y xs = snd . head $ filter (((==) y) . fst) xs

delete :: String -> [(String, a)] -> [(String,a)]
delete y xs = filter (not . ((==) y) . fst) xs

filter takes a predicate function (which is your search function of type String -> Bool) and a list and returns all of the elements of the list that satisfy the predicate. So for delete, we simply ask for all elements of our list that are not the one we are looking for. For find, we ask for all elements of our list that match, and then get the snd element of the first result of the list.

Fair warning, since find here uses head, if you're element is not in the list, it will throw an exception and if there is more than one matching result, it will return the first one.

Upvotes: 3

Related Questions