简体   繁体   English

haskell错误,压缩列表

[英]haskell Error,Zipping lists

I am learning Haskell and i try to write a code which somehow zips two lists. 我正在学习Haskell,我尝试编写一个代码,以某种方式拉链两个列表。 MY code should return me these list in these inputs 我的代码应该在这些输入中返回这些列表

Inputs: 输入:

[1,2,3] [6,5,4] 

[1,2,3] [6,5]

[1,2] [6,5,4]

outputs: 输出:

[(1,6),(2,5),(3,4)]
[(1,6),(2,5),(3,3)]
[(1,6),(2,5),(4,4)]

My code is this 我的代码是这样的

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)     

I am looking forward for your responces 我很期待你的回应

The problem is that you're taking a two lists with different element types, and then when one runs out attempting to use the other lists elements in place of it. 问题是你正在使用具有不同元素类型的两个列表,然后当一个列表试图使用其他列表元素代替它时。 This won't work since they don't have the same type. 这不起作用,因为它们没有相同的类型。

The simplest solution is just to fix the type signature to 最简单的解决方案就是将类型签名修复为

 zip' :: [a] -> [a] -> [(a, a)]

The other option, which I only mention because you had Integral constraints originally, is to try to convert between each element of the list. 另一个选项,我只提到因为你最初有Integral约束,是试图在列表的每个元素之间进行转换。

 zip' :: (Integral i, Integral j) => [i] -> [j] -> [(i, j)]

And now you're bmi 's would look like this 现在你的bmi看起来像这样

  ...
   where bmi x = (x, fromIntegral x)
  ...
    where bmi x = (fromIntegral x, x)
  ...
    where bmi x y = (x, y)

Strip away that bmi and just inline the tuples (that's what the compiler will do anyway), then it becomes more obvious what's wrong: 去除那个bmi并且只是内联元组(这就是编译器将要做的事情),然后更明显的是什么是错的:

zip' (x:xs)[]  = (x,x) : zip' xs []

You have (x,x) here, which obviously has the type of a homogenous tuple, but with the (i,b) signature you allow for arbitrary combinations of different types. 这里有(x,x) ,它显然具有同质元组的类型,但是(i,b)签名允许不同类型的任意组合。

In case you think such an intermediate function like bmi somehow switches on type conversions , nope, there are never implicit type conversions in Haskell! 如果您认为像bmi这样的中间函数会以某种方式切换类型转换 ,那么在Haskell中永远不会有隐式类型转换! (For very good reasons you'll soon appreciate with a bit more experience). (非常好的理由,你很快就会体会到更多经验)。

Type conversion must always be made explicit. 必须始终明确表示类型转换。 In your case that's indeed possible, using that Integral constraint: any two Integral type can be converted to one another with fromIntegral . 在您确实可能的情况下,使用该Integral约束:任何两个Integral类型都可以使用fromIntegral转换为另一个。

zip' (x:xs) []  = (       x       , fromIntegral x ) : zip' xs []
zip' [] (y:ys)  = ( fromIntegral y,        y       ) : zip' [] ys

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM