Home > Mobile >  How can I fix my haskell value code and give back the rest of the list?
How can I fix my haskell value code and give back the rest of the list?

Time:03-20

Key-value pairs Specify the function that retrieves the value for a given key from a list of key-value pairs. If the key is not listed, return a default value. The first parameter of the function should be the key to be searched, the second should be the default value, and the third should be the list!

I would like to give back the rest of the list, but I do not know how can I make it in my code. Can anybody help ?

value :: Eq a => a -> b -> [(a, b)] -> b
value a b ((c, d): xs)
  | a == c = d
  | otherwise = b     -- : value xs ?

Examples:
value "aaa" "notFound" [] == "notFound"
value "1" "notFound" [("1", "haskell")] == "hasFell"
value 5 "" [(0, "c   "), (5, "python"), (4, "rust")] == "python"
value 4 "" [(0, "c   "), (5, "python"), (4, "rust")] == "rust"
value 4 "" [(0, "c   "), (5, "python"), (4, "go")] == "go"
value 5 "scala" [(0, "c   "), (5, "python")] == "python"
value 3 "scala" [(0, "c   "), (1, "java"), (5, "python"), (4, "rust")] == "scala"
value 'b' False [('a', False), ('b', True)] == True

CodePudding user response:

There are three cases to consider:

  1. The list is empty
  2. The list is not empty, and the key matches the first pair.
  3. The list is not empty, and the key does not match the first pair.

You correctly identified what to do for case 2, but you did not consider case 1. In case 3, you have the same kind of lookup to do, but now with a shorter list (since you can ignore the first pair); you just need to recurse with appropriate arguments.

value :: Eq a => a -> b -> [(a, b)] -> b
value key def [] = ?  -- What do you return when the list is empty
value key def ((k, v):rest) | key == k = v
                            | otherwise = value ? ? ?  -- What arguments do you pass now?

Hint: the empty-list case is important not just because you want to cover all possibilities, but because if you need to return the default value, the recursive call will eventually be called on the empty list.

  • Related