我是 Haskell 的初学者,我有一个练习,其中的想法是创建多态函数。
我想创建一个函数,它接受列表和另一个要添加到该列表中的参数。
addA :: a -> [a] -> [a]
addA [] = []
addA (x: xs) = x + a : addA xs
在最后一行有一个错误显示:说变量 a 不在范围内并且 ->
Couldn't match expected type: [a1]
with actual type: [[a1]] -> [[a1]]
• Probable cause: ‘addA’ is applied to too few arguments
In the second argument of ‘(:)’, namely ‘addA xs’
In the expression: x + a : addA xs
In an equation for ‘addA’: addA (x : xs) = x + a : addA xs
• Relevant bindings include
xs :: [a1]
我不知道如何在列表中的每个元素中添加输入。
我们来看看
addA
的签名有什么:
addA :: a -> [a] -> [a]
这意味着为了调用
addA
,您需要提供两个参数。
但是,按照你的定义:
addA [] = [] -- There is only one parameter specified on the left side of '=', i.e. []
addA (x: xs) = x + a : addA xs -- There is only one parameter specified on the left side of '=', i.e. (x:xs)
这就是编译器所抱怨的。
如果您不确定如何正确实现算法但想通过类型检查,您可以使用丢弃模式(
_
):
addA _ [] = []
addA _ (x: xs) = x + a : addA xs