我是新的Haskell并尝试练习我的Haskell技能.
我想实现一个函数来合并两个列表,以便从每个列表中替换项目.
["a", "b", "c"]
["1", "2", "3"]
Run Code Online (Sandbox Code Playgroud)
合并后.
["a", "1", "b", "2", "c", "3"]
Run Code Online (Sandbox Code Playgroud)
这是我的Haskell代码
mergeList::[String]->[String]->[String]
mergeList [] [] = []
mergeList _ [] = []
mergeList [] _ = []
mergeList (x:xs) (y:ys) = x:y:mergeList xs ys
Run Code Online (Sandbox Code Playgroud)
只要两个列表的长度相同,代码就可以工作.
但是我想对两个列表的长度进行一些错误检查.
如果两个列表的长度不同,那么我想报告错误.
mergeList::[String]->[String]->[String]
mergeList l r | length l /= length r = error "report an error"
| otherwise =
Run Code Online (Sandbox Code Playgroud)
我怎样才能完成其他部分?
error不鼓励使用.在Haskell中,我们喜欢为所有可能的输入定义函数,以便类型系统可以指导我们编写正确的程序.如果您的函数对于不同长度的列表无效,则可以使用一种方法Maybe.
mergeList :: [a] -> [a] -> Maybe [a]
mergeList [] [] = Just []
mergeList (x:xs) (y:ys) =
case mergeList xs ys of
Just merged -> Just (x:y:merged)
Nothing -> Nothing
mergeList _ _ = Nothing
Run Code Online (Sandbox Code Playgroud)
有更简洁的方式来写这个,但我住在一楼附近.
现在,用户mergeList需要定义在传递两个不同长度的列表的情况下要做什么.
| 归档时间: |
|
| 查看次数: |
985 次 |
| 最近记录: |