我正在学习Haskell,我尝试编写一个代码,以某种方式拉链两个列表.我的代码应该在这些输入中返回这些列表
输入:
[1,2,3] [6,5,4]
[1,2,3] [6,5]
[1,2] [6,5,4]
Run Code Online (Sandbox Code Playgroud)
输出:
[(1,6),(2,5),(3,4)]
[(1,6),(2,5),(3,3)]
[(1,6),(2,5),(4,4)]
Run Code Online (Sandbox Code Playgroud)
我的代码是这样的
zip' :: (Integral i, Integral b) => [i] -> [b] -> [(i,b)]
zip' [][] = []
zip' (x:xs)[] = bmi x : zip' xs []
where bmi x = (x,x)
zip' [](x:xs) = bmi x : zip' [] xs
where bmi x = (x,x)
zip' (x:xs) (y:ys) = bmi x y : zip' xs ys
where bmi x y = (x,y)
Run Code Online (Sandbox Code Playgroud)
我很期待你的回应
问题是你正在使用具有不同元素类型的两个列表,然后当一个用完时尝试使用其他列表元素代替它.这不起作用,因为它们没有相同的类型.
最简单的解决方案就是将类型签名修复为
zip' :: [a] -> [a] -> [(a, a)]
Run Code Online (Sandbox Code Playgroud)
另一个选项,我只提到因为你原来有Integral约束,是试图在列表的每个元素之间进行转换.
zip' :: (Integral i, Integral j) => [i] -> [j] -> [(i, j)]
Run Code Online (Sandbox Code Playgroud)
现在你bmi看起来像这样
...
where bmi x = (x, fromIntegral x)
...
where bmi x = (fromIntegral x, x)
...
where bmi x y = (x, y)
Run Code Online (Sandbox Code Playgroud)