Bunny Rabbit
Bunny Rabbit

Reputation: 8411

how to resolve couldn't match expected type in 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

I am getting the follwing error while executing the above haskell code. What does this mean ? My understanding is that the type returned by fromInteger (Integer) is not same as the type returned by returned by (Int). How can I fix this ?

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

Upvotes: 1

Views: 398

Answers (1)

zigazou
zigazou

Reputation: 1755

You can replace fromInteger with fromIntegral.

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

It works because Int complies with the Integral class while fromInteger only accepts Integer as parameter.

Upvotes: 3

Related Questions