繁体   English   中英

无法推断......背景Ord Haskell

[英]Could not deduce …context Ord Haskell

出于学习目的,我试图将2个列表压缩在一起,只要两个匹配的长度匹配。 (必须是相同的长度)不幸的是,它拒绝编译。 我认为签名有问题。谢谢你的期待。 这是我的代码:

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约束。 如果您打算使用<或类似的操作,则只需要此操作。

暂无
暂无

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

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