如何解决与haskell

时间:2015-12-29 12:14:49

标签: haskell

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)'

1 个答案:

答案 0 :(得分:3)

您可以将fromInteger替换为fromIntegral

fromInteger :: Num a => Integer -> a
fromIntegral :: (Integral a, Num b) => a -> b

它有效,因为Int符合Integral类,而fromInteger仅接受Integer作为参数。