سؤال

I'm trying to do a haskell one-liner to compute the Taylor Series of e^x with this attempt:

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

But I keep running into this issue:

<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

I don't think I fully understand whats going wrong here - could someone explain it to me?

هل كانت مفيدة؟

المحلول

You can fix it with:

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

The type of your function is (Fractional t, Integral t) => t -> [t]

The error indicates that it is ambiguous which type you want to use for t. There doesn't seem to actually be such a type. The reason for the Integral constraint is your use of ^. If you replace it with (**) then the type of expt changes to

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

and you can then use Double or Float.

نصائح أخرى

The nth term of the Taylor series is x^n/n!, so the terms are computed by

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

I have no idea what you were trying to do with the separate e and n variables.

Try this:

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

We've done two things:

  1. Specified an explicit integral type for e
  2. Converted the factorial (which is now an Int) into a Fractional instance with fromIntegral

You can still use any Fractional instance for x - e.g. Float, Double, etc.

Note: for 32-bit ints this will be good for about 12 terms.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top