我正在编写Haskell代码,练习尾递归来反转列表,并提出了这个解决方案:
reverseh' [] list = list
reverseh' (x:xs) list = reverseh' (xs) (x ++ list)
reverse' x = reverseh' x []
它仅适用于列表列表,但我希望它具有类型签名[a] -> [a]
。
请你解释我在这里做错了什么?
答案 0 :(得分:9)
如果你没有得到预期的类型,最好添加一个显式类型签名来告诉编译器你想要的类型,在这里:
reverseh' :: [a] -> [a] -> [a]
然后你得到一个编译错误:
Couldn't match expected type `[a]' with actual type `a'
`a' is a rigid type variable bound by
the type signature for reverseh' :: [a] -> [a] -> [a]
at reverseh.hs:1:14
Relevant bindings include
list :: [a] (bound at reverseh.hs:3:18)
xs :: [a] (bound at reverseh.hs:3:14)
x :: a (bound at reverseh.hs:3:12)
reverseh' :: [a] -> [a] -> [a] (bound at reverseh.hs:2:1)
In the first argument of `(++)', namely `x'
In the second argument of reverseh', namely `(x ++ list)'
这告诉您,在(x ++ list)
中,x
需要为[a]
类型才能进行类型检查,但是考虑到类型签名,x
确实属于a
类型。因此,您希望将++
替换为a -> [a] -> [a]
类型的函数,这样您就可以使用(x : list)
。
答案 1 :(得分:3)
由于第二行中的(x ++ list)
表达式,typechecker认为x :: [a]
。我想你想写(x : list)
。