为什么以下haskell函数会出错?
目的是在列表中复制给定元素k次并返回列表。
功能:
--Replicate the element given number of times and return the list.
replicateElement :: (Integral k) => a -> k -> [a]
replicateElement x 0 = error "Cannot replicate Zero times"
replicateElement x 1 = [x]
replicateElement x k = [x] ++ replicateElement(x k-1)
错误:
Couldn't match expected type `[a]' with actual type `k0 -> [a0]'
In the return type of a call of `replicateElement'
Probable cause: `replicateElement' is applied to too few arguments
In the second argument of `(++)', namely
`replicateElement (x k - 1)'
In the expression: [x] ++ replicateElement (x k - 1)
Failed, modules loaded: none.
答案 0 :(得分:3)
写作时
replicateElement(x k-1)
您只将一个参数传递给replicateElement
,即(x k-1)
,这也意味着((x k) - 1)
,而您实际上并不打算让x
成为一个函数。相反,你应该写的是:
replicateElement x (k-1)
答案 1 :(得分:1)
你的最后一行应该是:
replicateElement x k = [x] ++ replicateElement x (k-1)
您不需要在Haskell中为函数参数添加括号。