myreplica :: (Num a,Ord a) => a -> b -> [b]
myreplica num val
| num <= 0 = []
| otherwise = [val] ++ myreplica (num-1) val
上面的函数取两个值Num和Val并返回一个List L = [val,val ... num times]。代码适用于0和正值但是当我给出输入时
"ghci> " replicate' -1 123
<interactive>:72:1:
Non type-variable argument in the constraint: Num (i -> a -> [a])
(Use FlexibleContexts to permit this)
When checking that ‘it’ has the inferred type
it :: forall i a a1.
(Num i, Num a1, Num (i -> a -> [a]), Num (a1 -> i -> a -> [a]),
Ord i) =>
i -> a -> [a]
我收到以下错误消息。如何使其适用于负数? 为什么我们需要(Num a,Ord a)约束?
答案 0 :(得分:3)
用括号括起负数,即myreplica (-1) 123
。但是,您可能希望在第一个参数中使用error
为负数添加一个特殊情况,因为重复一些负数是没有意义的。
答案 1 :(得分:0)
你真的不需要(Num a, Ord a)
,但它是可重新调整的,同时注意最好使用(:)
函数代替&#39;(++)&#39;如下:
myreplica :: (Num a,Ord a) => a -> b -> [b]
myreplica num val
| num <= 0 = []
| otherwise = val : myreplica (num-1) val