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开发者_StackOverflow中文版 type, but I don't know how to fix code to work with Integer parameters.
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.
You can use fromIntegral
to convert any Integral type into any Num type. So:
let y = fromIntegral a / fromIntegral b
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)
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)
精彩评论