Searching through list of tuples

后端 未结 3 425
别那么骄傲
别那么骄傲 2021-01-28 10:20

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

3条回答
  •  我在风中等你
    2021-01-28 10:38

    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)
    

提交回复
热议问题