什么是正确的方法来划分两个Int值来获得Float? [英] What's the right way to divide two Int values to obtain a Float?

查看:202
本文介绍了什么是正确的方法来划分两个Int值来获得Float?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Haskell中分两个 Int 值并获得结果作为 Float 。我尝试这样做:

  foo :: Int  - > Int  - >浮动
foo ab = fromRational $ a%b

但GHC(版本6.12.1)告诉我对于表达式中 a 的推断类型'Int',无法匹配预期的类型'整数'。



我明白为什么: fromRational 调用要求(%)产生一个 Ratio Integer ,所以操作数必须是 Integer 而不是 Int 。但是我分割的值远不及 Int 的范围限制,所以使用任意精度的bignum类型似乎是过度杀伤。 $ b

正确的做法是什么?我应该在我的操作数上调用到Integer ,还是有一个更好的方法(也许不涉及(%)和比率),我不知道?

解决方案

您必须将操作数转换为浮动 first 然后除,否则你将执行一个整数除法(无小数位)。

Laconic解决方案(需要 Data.Function
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ / pre>



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

with

  foo :: Int  - > Int  - >浮动


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?

解决方案

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

这篇关于什么是正确的方法来划分两个Int值来获得Float?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆