12

I'm having some problem with one of the functions which I'm new at, it's the fromIntegral function.

Basically I need to take in two Int arguments and return the percentage of the numbers but when I run my code, it keeps giving me this error:

Code:

percent :: Int -> Int -> Float
percent x y =   100 * ( a `div` b )
where   a = fromIntegral x :: Float
        b = fromIntegral y :: Float

Error:

No instance for (Integral Float)
arising from a use of `div'
Possible fix: add an instance declaration for (Integral Float)
In the second argument of `(*)', namely `(a `div` b)'
In the expression: 100 * (a `div` b)
In an equation for `percent':
    percent x y
      = 100 * (a `div` b)
      where
          a = fromIntegral x :: Float
          b = fromIntegral y :: Float

I read the '98 Haskell prelude and it says there is such a function called fromInt but it never worked so I had to go with this but it's still not working. Help!

1
  • 1
    I doubt the 98 report claims there is a fromInt. Commented Apr 24, 2012 at 18:04

2 Answers 2

26

Look at the type of div:

div :: Integral a => a -> a -> a

You cannot transform your input to a Float and then use div.

Use (/) instead:

(/) :: Fractional a => a -> a -> a

The following code works:

percent :: Int -> Int -> Float
percent x y =   100 * ( a / b )
  where a = fromIntegral x :: Float
        b = fromIntegral y :: Float
Sign up to request clarification or add additional context in comments.

3 Comments

Oh, cheers for the heads up, I have been using div the whole time and forgot to look at the alternative! My bad, thanks again!
For concision, you don't need to force the type :: Float
Using Data.Function.on you can write percent x y = 100 * ((/) 'on' fromIntegral) x y (replace ' by backticks)
0

alternatively you can do

precent :: Int -> Int -> Float
percent x y = 100 * ( int(a) / int(b) ) 
  where int = fromIntegral

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.