I\'m trying to write a function that accepts a string and a list of tuple pairs. I want to search through the list of tuples, and if the first value in the tuple matches the inp
In the base case, if list is empty, it returns Nothing. Then, if first element a of tuple in the head is equal to element x, it returns second element Just b. Else, recursively, it searchs in the tail.
search :: (Eq a) => a -> [(a,b)] -> Maybe b
search _ [] = Nothing
search x ((a,b):xs) = if x == a then Just b else search x xs
You can implement an unsafe version without Maybe:
search :: (Eq a) => a -> [(a,b)] -> b
search _ [] = error "element not found"
search x ((a,b):xs) = if x == a then b else search x xs
Other option is searching a list instead of first ocurrence, then, empty list [] is equivalent to Nothing:
search :: (Eq a) => a -> [(a,b)] -> [b]
search x = map snd . filter ((==x).fst)