Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 无法推断…哈斯克尔_Haskell - Fatal编程技术网

Haskell 无法推断…哈斯克尔

Haskell 无法推断…哈斯克尔,haskell,Haskell,出于学习目的,我尝试将两个列表压缩在一起,前提是两个列表的长度都匹配。(长度必须相同)不幸的是,它拒绝编译。 我想签名有问题。。谢谢你的期待。 这是我的密码: ziptogether :: (Ord a) => [a] -> [a] -> [a] ziptogether [] [] = 0 ziptogether (x:xs) (y:ys) | length(x:xs) == length(y:ys) = zip (x:xs) (y:xs) | otherwise

出于学习目的,我尝试将两个列表压缩在一起,前提是两个列表的长度都匹配。(长度必须相同)不幸的是,它拒绝编译。 我想签名有问题。。谢谢你的期待。 这是我的密码:

ziptogether :: (Ord a) => [a] -> [a] -> [a]
ziptogether [] [] = 0
ziptogether (x:xs) (y:ys) 
   | length(x:xs) == length(y:ys) = zip (x:xs) (y:xs)
   | otherwise = error "not same length"
错误:

     Could not deduce (a ~ (a, a))
     from the context (Ord a)
      bound by the type signature for
                ziptogether :: Ord a => [a] -> [a] -> [a]
      at new.hs:2:16-43
         `a' is a rigid type variable bound by
         the type signature for ziptogether :: Ord a => [a] -> [a] -> [a]
         at new.hs:2:16
    Expected type: [a]
     Actual type: [(a, a)]
    In the return type of a call of `zip'
    In the expression: zip (x : xs) (y : xs)
    In an equation for `ziptogether':
    ziptogether (x : xs) (y : ys)
      | length (x : xs) == length (y : ys) = zip (x : xs) (y : xs)
      | otherwise = error "not same length"

有几个问题。您的类型签名表示您获取两个列表并返回另一个列表,您的第一个问题是

 ziptogether [] [] = 0
所以这需要元素并返回。。一个数字。我想你想要

 ziptogether [] [] = []
下一个问题是递归调用
zip
,它返回
[(a,a)]
。您可以将您的类型签名更改为

 ziptogether :: [a] -> [a] -> [(a, a)]
 ziptogether [] [] = []
 ziptogether (x:xs) (y:ys) | length xs == length ys = zip (x:xs) (y:ys)
                           | otherwise = error "Not the same length"
当然,你可以在这里消除多余的情况

 ziptogether xs ys | length xs == length ys = zip xs ys
                   | otherwise              = error "Not the same length"

请注意,我们不需要
Ord
约束。仅当您计划使用
之类的操作时才需要此选项,非常感谢!我有一个问题,你为什么忽略了“Ord(a)”。我们不是在比较这两个列表吗?我们正在比较两者的长度。为什么这里不需要Ord?@user2938633两个列表的长度是一个
Int
,列表中的内容无关紧要,它的长度只是一个数字。如果我们想比较元素,那么我们需要一些约束。但我们没有,所以我们没有。好的,明白了,谢谢。第二个问题。它现在可以编译了,但它没有做到这一点。。在您的更正之后,我更改了代码,当我键入ziptogether[1,2,3,4][5,6,7,8]时,它会给出[(1,1),(2,2)(3,3),(4,4)]。为什么?@user2938633恐怕我无法复制这种行为哦,真是个错误。我无意中编写了zip xs xs而不是zip xs ys。我真丢脸!不过,非常感谢jozefg。又帮了我很多忙!