如何修复我的 haskell 值代码并返回列表的其余部分?
How can I fix my haskell value code and give back the rest of the list?
键值对
指定从键值对列表中检索给定键的值的函数。如果键未列出,return 默认值。函数的第一个参数应该是要查找的key,第二个参数应该是默认值,第三个参数应该是列表!
我想返回列表的其余部分,但我不知道如何在我的代码中实现它。有人可以帮忙吗?
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
有 三种 种情况需要考虑:
- 列表为空
- 列表不为空,键匹配第一对。
- 列表不为空,密钥不匹配第一对。
您正确地确定了针对案例 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?
提示:empty-list 案例很重要,不仅因为您想涵盖所有可能性,还因为如果您需要 return 默认值,递归调用 将最终在空列表上被调用。
键值对 指定从键值对列表中检索给定键的值的函数。如果键未列出,return 默认值。函数的第一个参数应该是要查找的key,第二个参数应该是默认值,第三个参数应该是列表!
我想返回列表的其余部分,但我不知道如何在我的代码中实现它。有人可以帮忙吗?
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
有 三种 种情况需要考虑:
- 列表为空
- 列表不为空,键匹配第一对。
- 列表不为空,密钥不匹配第一对。
您正确地确定了针对案例 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?
提示:empty-list 案例很重要,不仅因为您想涵盖所有可能性,还因为如果您需要 return 默认值,递归调用 将最终在空列表上被调用。