我正在浏览http://learnyouahaskell.com/recursion,并实现了复制,
replicate' :: (Num a, Ord a) => a -> b -> [b]
replicae' 0 _ = []
replicate' n x
| n < 0 = []
| n > 0 = [x] ++ replicate' (n - 1) x
决定尝试使用负重复次数,得到错误:
ghci> replicate' -1 42
<interactive>:35:1: error:
• Could not deduce (Num t0)
arising from a type ambiguity check for
the inferred type for ‘it’
from the context: (Ord i, Num i, Num t, Num (t -> i -> a -> [a]),
Num (i -> a -> [a]))
bound by the inferred type for ‘it’:
forall {i} {t} {a}.
(Ord i, Num i, Num t, Num (t -> i -> a -> [a]),
Num (i -> a -> [a])) =>
i -> a -> [a]
at <interactive>:35:1-16
The type variable ‘t0’ is ambiguous
These potential instances exist:
instance Num Integer -- Defined in ‘GHC.Num’
instance Num Double -- Defined in ‘GHC.Float’
instance Num Float -- Defined in ‘GHC.Float’
...plus two others
...plus two instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the ambiguity check for the inferred type for ‘it’
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
When checking the inferred type
it :: forall {i} {t} {a}.
(Ord i, Num i, Num t, Num (t -> i -> a -> [a]),
Num (i -> a -> [a])) =>
i -> a -> [a]
我想:“也许我做错了什么。”并尝试了书中的例子;与相同的结果
replicate' :: (Num i, Ord i) => i -> a -> [a]
replicate' n x
| n <= 0 = []
| otherwise = x:replicate' (n-1) x
GHCi,版本9.2.4
代码出了什么问题,为什么书中的例子也不起作用?
1条答案
按热度按时间biswetbf1#
在你的表情中:
运算符
-
被误解为二进制运算符-
,所以这相当于:所以Haskell试图将“函数”
1
应用于参数42
,然后从函数replicate'
中减去结果。结果是一个难以理解的错误消息。试试看:
应该能正常工作
请注意,您最初的
replicate'
定义在第二行将函数拼写为replicae'
,因此请确保也已修复。