为什么这个函数需要一个 [[a]]?
Why does this function take an [[a]]?
我正在编写 Haskell 代码练习尾递归来反转列表并提出了这个解决方案:
reverseh' [] list = list
reverseh' (x:xs) list = reverseh' (xs) (x ++ list)
reverse' x = reverseh' x []
它只适用于列表的列表,但我希望它具有类型签名 [a] -> [a]
。
你能解释一下我做错了什么吗?
因为第二行的(x ++ list)
表达式,typechecker认为x :: [a]
。我想你想写 (x : list)
。
如果你没有得到预期的类型,最好添加一个显式类型签名来告诉编译器你想要的类型是什么,这里:
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)
.
我正在编写 Haskell 代码练习尾递归来反转列表并提出了这个解决方案:
reverseh' [] list = list
reverseh' (x:xs) list = reverseh' (xs) (x ++ list)
reverse' x = reverseh' x []
它只适用于列表的列表,但我希望它具有类型签名 [a] -> [a]
。
你能解释一下我做错了什么吗?
因为第二行的(x ++ list)
表达式,typechecker认为x :: [a]
。我想你想写 (x : list)
。
如果你没有得到预期的类型,最好添加一个显式类型签名来告诉编译器你想要的类型是什么,这里:
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)
.