示例replicate'来自“学习一些Haskell”关于递归的章节

ncgqoxb0  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(113)

我正在浏览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
代码出了什么问题,为什么书中的例子也不起作用?

biswetbf

biswetbf1#

在你的表情中:

replicate' -1 42

运算符-被误解为二进制运算符-,所以这相当于:

replicate' - (1 42)

所以Haskell试图将“函数”1应用于参数42,然后从函数replicate'中减去结果。结果是一个难以理解的错误消息。
试试看:

replicate' (-1) 42

应该能正常工作
请注意,您最初的replicate'定义在第二行将函数拼写为replicae',因此请确保也已修复。

相关问题