tags:

views:

84

answers:

4
+4  Q: 

Integer to float

This code works:

posToXY :: Float -> Float -> Integer
posToXY a b = do
        let y = a / b
        round y

But this doesn't work:

posToXY :: Integer -> Integer -> Integer
posToXY a b = do
        let y = a / b
        round y

I understand that operation '/' doesn't define for Integer type, but I don't know how to fix code to work with Integer parameters.

+3  A: 

You can use fromIntegral to convert any Integral type into any Num type. So:

let y = fromIntegral a / fromIntegral b
sepp2k
+3  A: 

Your code could easily be simplified to

posToXY :: Float -> Float -> Integer
posToXY a b = round (a / b)

Then

posToXY :: Integer -> Integer -> Integer
posToXY a b = round (fromIntegral a / fromIntegral b)
supercooldave
+5  A: 

If you want to perform fractional division, you can convert from any Integral type using fromIntegral, or fromInteger to convert only from Integer specifically.

There are similar functions relating to other numeric type classes: toRational, fromRational, realToFrac, etc. And of course you can convert fractional types back to integral types using round, floor, ceiling, or such.

And finally, on the off chance that you actually wanted integer division, instead of fractional division with rounding afterwards, there's the div and quot functions (depending on what truncation behavior you want).

Also, you probably should write your function as something like posToXY a b = round $ a / b. The unnecessary do and multiple lines makes it harder to read.

camccann
`posToXY a b = round $ a / b` -- in this case, I personally prefer parentheses for readability - it saves having to think (even for just a split second) about operator precedence, and it just looks more like the mathematical expression it represents.
mokus
@mokus: Yeah, I agree. I only used `($)` here out of habit, I likely would've used parentheses in actual code.
camccann
+3  A: 

If you want integer division, you can use div.

posToXY :: Integer -> Integer -> Integer
posToXY = div

Note this isn't quite the same as rounding a floating-point division, because div always rounds down.

For a more general type signature, you can do this instead

p :: (Real a, Real a1, Integral b) => a -> a1 -> b
posToXY a b = round (realToFrac a / realToFrac b)
John