Home > database >  How can I implement this function in haskell?
How can I implement this function in haskell?

Time:10-24

I need to implement the find function, which retrieves the value associated with a particular key from a list of key-value pairs belongs to. The key value pairs are defined by simple tuples.

Example:

find 2 [(3,"xy"),(2,"abc"),(4,"qwe")] == "abc"

find  42 [(1,2),(3,4),(42,42)] == 42

My code:

find :: Eq a => a -> [(a, b)] -> b
find 'x (a, b)
  | x == a = b

CodePudding user response:

find :: Eq a => a -> [(a, b)] -> Maybe b
find _ [] = Nothing
find x ((a, b):xs)
  | x == a = Just b
  | otherwise = find x xs

I took the liberty to change the return type of the function signature to Maybe b to cover the case when the searched value is not found. That's customary in these situations in Haskell, as far as I know.

There are 2 basic patterns. If the list is exhausted and no result was found previously, return Nothing. Otherwise, check if it's a match, if so return the value wrapped in Just, otherwise recurse further searching.

  • Related