[Haskell-cafe] Type conversion problems
Lauri Alanko
la at iki.fi
Sun Jun 13 06:25:52 EDT 2004
On Sun, Jun 13, 2004 at 11:15:28AM +0200, Christian Hofer wrote:
> fac :: Integer -> Integer
> fac n = product [1..n]
>
> term :: Double -> Integer -> Double
> term x n = (-1.0::Double)**(fromInteger n) * (x**(fromInteger (2*n +
> 1))) /
> (fromInteger (fac (2*n + 1)))
Why do you have all those type annotations? Simply writing directly:
fac n = product [1..n]
term x n = -1 ** n * (x ** (2 * n + 1)) / fac (2 * n + 1)
gives you functions for which are inferred the types (which you can of
course also give explicitly if you want):
fac :: (Enum a, Num a) => a -> a
term :: (Floating a, Enum a) => a -> a -> a
And the type variable a can then be instantiated for Double. If you
really need to take an Integer parameter, you only need a single
conversion:
term' x n = term x (fromIntegral n)
with the type:
term' :: (Floating a, Enum a, Integral b) => a -> b -> a
If all this looks confusing, then forget about polymorphism and just
give exact types in the type annotations:
fac :: Double -> Double
fac n = product [1..n]
term :: Double -> Double -> Double
term x n = -1 ** n * (x ** (2 * n + 1)) / fac (2 * n + 1)
term' :: Double -> Integer -> Double
term' x n = term x (fromIntegral n)
Hope this helps.
Lauri Alanko
la at iki.fi
More information about the Haskell-Cafe
mailing list