整数 `x を指定してe x (最初の 10 項) を計算する関数を作成しようとしています。
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)
ここで上で行っていることは、2 つの整数結果 (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