1

我正在尝试做一个haskell one-liner来计算e^x的泰勒级数:

-- 1 + x^1/1! + x^2/2! + x^3/3! + ...
expt x = [(x^e) / (product [1..n]) | e <- [0..], n <- [1..e]]

但我一直遇到这个问题:

<interactive>:5:1:
    No instance for (Integral t0) arising from a use of `expt'
    The type variable `t0' is ambiguous
    Possible fix: add a type signature that fixes these type variable(s)
    Note: there are several potential instances:
      instance Integral Int -- Defined in `GHC.Real'
      instance Integral Integer -- Defined in `GHC.Real'
      instance Integral GHC.Types.Word -- Defined in `GHC.Real'
    In the expression: expt 2
    In an equation for `it': it = expt 2

<interactive>:5:6:
    No instance for (Num t0) arising from the literal `2'
    The type variable `t0' is ambiguous
    Possible fix: add a type signature that fixes these type variable(s)
    Note: there are several potential instances:
      instance Num Double -- Defined in `GHC.Float'
      instance Num Float -- Defined in `GHC.Float'
      instance Integral a => Num (GHC.Real.Ratio a)
        -- Defined in `GHC.Real'
      ...plus three others
    In the first argument of `expt', namely `2'
    In the expression: expt 2
    In an equation for `it': it = expt 2

我不认为我完全理解这里出了什么问题 - 有人可以向我解释一下吗?

4

3 回答 3

4

您可以使用以下方法修复它:

 expt x = [(x ** e) / (product [1..n]) | e <- [0..], n <- [1..e]]

你的函数类型是(Fractional t, Integral t) => t -> [t]

该错误表明您要使用的类型不明确t。实际上似乎没有这种类型。约束的原因Integral是您使用^. 如果将其替换为(**)then 的类型expt更改为

(Enum t, Floating t) => t -> [t]

然后你可以使用Doubleor Float

于 2014-04-14T19:43:04.120 回答
1

泰勒级数的第 n 项是 x^n/n!,因此这些项由下式计算

expt x = [x**n / (product [1..n]) | n <- [0..]]

我不知道你想用单独的 e 和 n 变量做什么。

于 2014-04-15T01:35:49.793 回答
0

试试这个:

expt x = [(x^e) / (fromIntegral $ product [1..n]) | e <- [(0::Int)..], n <- [1..e]]

我们做了两件事:

  1. e
  2. 将阶乘(现在是一个Int)转换为一个Fractional实例fromIntegral

您仍然可以使用任何Fractional实例x- 例如Float,Double等。

注意:对于 32 位整数,这将适用于大约 12 个术语。

于 2014-04-14T19:46:31.430 回答