Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Converting Int to Float

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!

like image 615
Syafiq Kamarul Azman Avatar asked Apr 24 '12 17:04

Syafiq Kamarul Azman


People also ask

What does fromIntegral do Haskell?

The workhorse for converting from integral types is fromIntegral , which will convert from any Integral type into any Num eric type (which includes Int , Integer , Rational , and Double ): fromIntegral :: (Num b, Integral a) => a -> b.

What is the difference between Int and Integer in Haskell?

What's the difference between Integer and Int ? Integer can represent arbitrarily large integers, up to using all of the storage on your machine. Int can only represent integers in a finite range. The language standard only guarantees a range of -229 to (229 - 1).


1 Answers

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
like image 168
Nicolas Dudebout Avatar answered Sep 22 '22 01:09

Nicolas Dudebout