fact :: Int -> Int
fact x = if x == 1 then x else x * fact(x - 1)
nterm :: Double -> Int -> Double
nterm x i = x ^ i / fromInteger (fact i)
solve :: Double -> Double
solve x = sum [nterm x i| i <- [1..10]] + 1
main :: IO ()
main = getContents >>= mapM_ print. map solve. map (read::String->Double). tail. words
我在执行上面的haskell代码时遇到了以下错误。这是什么意思 ?我的理解是fromInteger(Integer
)返回的类型与(Int
)返回的类型不同。
我怎样才能解决这个问题 ?
solution.hs:5:35:
Couldn't match expected type `Integer' with actual type `Int'
In the first argument of `fromInteger', namely `(fact i)'
In the second argument of `(/)', namely `fromInteger (fact i)'
答案 0 :(得分:3)
您可以将fromInteger
替换为fromIntegral
。
fromInteger :: Num a => Integer -> a
fromIntegral :: (Integral a, Num b) => a -> b
它有效,因为Int
符合Integral
类,而fromInteger
仅接受Integer
作为参数。