键值对指定从键值对列表中检索给定键的值的函数。如果键未列出,则返回默认值。函数的第一个参数应该是要搜索的键,第二个参数应该是默认值,第三个参数应该是列表!
我想返回列表的其余部分,但我不知道如何在代码中做到这一点。有人能帮忙吗?
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发布于 2022-03-19 21:58:37
有三个案件需要考虑:
您正确地确定了对案例2应该做什么,但是没有考虑案例1。在案例3中,您有相同的查找,但是现在有一个更短的列表(因为您可以忽略第一对);您只需要使用适当的参数来恢复。
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?提示:空列表的情况很重要,不仅因为您想要覆盖所有的可能性,而且因为如果您需要返回默认值,递归调用最终将在空列表上调用。
https://stackoverflow.com/questions/71542165
复制相似问题