我正在尝试编写一个函数,在给定整数 ` x .
e x的级数展开式由下式给出
1 + x + x2/2! + x3/3! + x4/4! + ....
该函数本身相当容易编写,但我似乎无法理解除法的 Haskell 类型规则,即我想将一个整数除以一个更大的整数并得到一个浮点结果:
这是我目前拥有的
_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
and factorial n
) 然后在浮点上下文中使用fromIntegral
and评估它们/
。但是,此函数返回此错误:
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