开发者

What's the right way to divide two Int values to obtain a Float?

开发者 https://www.devze.com 2023-01-08 07:06 出处:网络
I\'d like to divide two Int values in Haskell and obtain the result as a Float.I tried doing it like this:

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 开发者_StackOverflowwhy: 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?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号