1

当我尝试编译这段代码时

prod [] = 1
prod (x:xs) = x * prod xs

ff :: (Num a) => a -> a -> a
ff x n = prod [(x - n + 1) .. x]

我收到以下错误:

a.hs:5:15:
    Could not deduce (Enum a)
     arising from the arithmetic sequence `(x - n + 1) .. x'
    from the context (Num a)
      bound by the type signature for ff :: Num a => a -> a -> a
      at a.hs:5:1-32
    Possible fix:
      add (Enum a) to the context of
        the type signature for ff :: Num a => a -> a -> a
    In the first argument of `prod', namely `[(x - n + 1) .. x]'
    In the expression: prod [(x - n + 1) .. x]
    In an equation for `ff': ff x n = prod [(x - n + 1) .. x]

这段代码有什么问题?当我代替Double一个一切都好。

4

3 回答 3

7

[i .. j]是 的简写enumFromTo i jenumFromTo是类型类的一部分,而Enum不是Num(你仍然需要Num使用)的一部分。+-

所以你需要说a实现Enum以及实现Num

ff :: (Num a, Enum a) => a -> a -> a
ff x n = prod [(x - n + 1) .. x]

它适用,Double因为Double实现了这两个类型类。

于 2012-07-31T09:44:04.253 回答
2

为了[x .. y]工作,结果类型根本不需要是一个Num实例(例如,['A'..'Z']工作得很好)。它必须是一个Enum实例。只需添加Enum到类型签名。

它适用于Double因为Double有两个实例。

于 2012-07-31T09:33:13.373 回答
1

ff :: (Enum a, Num a) => a -> a -> a
ff x n = prod [(x - n + 1) .. x]

于 2012-07-31T09:32:08.303 回答