What's the right way to divide two Int values

2020-06-30 12:19发布

问题:

I'd like to divide two Int values in Haskell and obtain the result as a Float. I tried doing it like this:

foo :: Int -> Int -> Float
foo a b = fromRational $ a % b

but GHC (version 6.12.1) tells me "Couldn't match expected type 'Integer' against inferred type 'Int'" regarding the a in the expression.

I understand why: the fromRational call requires (%) to produce a Ratio Integer, so the operands need to be of type Integer rather than Int. But the values I'm dividing are nowhere near the Int range limit, so using an arbitrary-precision bignum type seems like overkill.

What's the right way to do this? Should I just call toInteger on my operands, or is there a better approach (maybe one not involving (%) and ratios) that I don't know about?

回答1:

You have to convert the operands to floats first and then divide, otherwise you'll perform an integer division (no decimal places).

Laconic solution (requires Data.Function)

foo = (/) `on` fromIntegral

which is short for

foo a b = (fromIntegral a) / (fromIntegral b)

with

foo :: Int -> Int -> Float