and*_*ndy 1 haskell functional-programming
如何定义一个带有两个列表和输出1列表的追加函数.
所以plusplus [1,2,3] [4,5,6]应该回来[1,2,3,4,5,6].
到目前为止,我有以下内容:
plusplus :: [Int] -> [Int] -> [Int]
plusplus [] [] = []
plusplus [] [x] = [x]
plusplus [x] [] = [x]
plusplus (x:xs) (y:ys) = x: plusplus xs (y:ys)
Run Code Online (Sandbox Code Playgroud)
我想定义自己的++函数,但是使用递归.当我用两个列表实际执行它时,上面的代码给出了一个错误.
这是我通过命令获得的错误示例:
plusplus [1,2,3] [4,5,6]
[1,2,3*** Exception: baby.hs:(...): Non-exhaustive patterns in function plusplus
Run Code Online (Sandbox Code Playgroud)
好吧基本上你在这里唯一的问题是缺少案例:
pluspluse (x:xs) [] = ...
Run Code Online (Sandbox Code Playgroud)
缺少(并会导致错误)
但你可以清理一下:
前两种情况基本相同:无论第二个输入是什么结果 - 所以你可以把它当作一个名字(比如说ys)并写:
plusplus [] ys = ys
Run Code Online (Sandbox Code Playgroud)
(你能看出这包括你的前两个案例吗? - 那些是什么ys?)
你的第3行将被正确的最后一个案例所覆盖(见下文) - 要记住这一点 [x] == x:[]
我会在几分钟内给你完整的答案 - 但你应该试着弄清楚:
plusplus :: [Int] -> [Int] -> [Int]
plusplus [] ys = ys
plusplus (x:xs) ? = ??
Run Code Online (Sandbox Code Playgroud)
尝试找到正确的东西来代替?,并??用
你几乎拥有它 - 答案可能是:
plusplus :: [Int] -> [Int] -> [Int]
plusplus [] ys = ys
plusplus (x:xs) ys = x: plusplus xs ys
Run Code Online (Sandbox Code Playgroud)
你可以看到你永远不必触摸第二个列表 - 但需要重新创建所有第一个列表(链接到第二个列表)
| 归档时间: |
|
| 查看次数: |
525 次 |
| 最近记录: |