我想写一个函数,计算电子x(前10项)给出一个整数`x。精度除以大整数
的级数为电子X由
1 + x + x2/2! + x3/3! + x4/4! + ....
给出的函数本身是相当容易写,但我似乎无法理解师哈斯克尔类型的规则,也就是我想要分割通过一个更大的整数一个整数,并得到一个浮点结果:
这里是我有那么目前
_eToX :: (Fractional a, Integral a) => a -> a -> a
_eToX x 0 = 1.0
_eToX x 1 = x
_eToX x n = (fromIntegral(x^n)/fromIntegral(factorial n)) + _eToX x (n - 1)
我在这里做的事情对我来说很有意义,计算两个整数结果(x^n
和factorial n
),然后使用fromIntegral
和/
在浮点上下文中对它们进行评估。然而,该函数返回该错误:
1. Could not deduce (a ~ Integer)
from the context (Fractional a, Integral a)
bound by the type signature for
_eToX :: (Fractional a, Integral a) => a -> a -> a
at /run-r4AWbVU9Fyph0OVhK3Dm/solution.hs:9:10-50
`a' is a rigid type variable bound by
the type signature for
_eToX :: (Fractional a, Integral a) => a -> a -> a
at /run-r4AWbVU9Fyph0OVhK3Dm/solution.hs:9:10
In the return type of a call of `factorial'
In the second argument of `(/)', namely `factorial n'
In the first argument of `(+)', namely `(x^n/factorial n)'
2. No instance for (Integral Double) arising from a use of `f'
Possible fix: add an instance declaration for (Integral Double)
In the expression: f
In the second argument of `($)', namely
`f $ map (read :: String -> Double) $ lines inputdata'
In the second argument of `($)', namely
`map show $ f $ map (read :: String -> Double) $ lines inputdata'
我正在使用此功能主要功能:
main = do
n <- readLn :: IO Int -- n doesnt really matter here because of getContents
inputdata <- getContents
mapM_ putStrLn $ map show $ f $ map (read :: String -> Double) $ lines inputdata
您可以使用'Rational',那么您不需要从整合 – DiegoNolan