Search code examples
haskelllist-comprehensiontaylor-series

Computing Taylor Series of e^x with Haskell List Comprension


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?


Solution

  • 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.