出于学习目的,我试图将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"
答案 0 :(得分:2)
有一些问题。你的类型签名说你拿两个列表并返回另一个,你的第一个问题是
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
约束。如果您打算使用<
或类似的操作,则只需要这样。