Haskell 中过度使用 fromIntegral
每当我使用双精度和整数编写函数时,我都会发现这个问题,我必须在函数中的任何地方不断地使用“fromIntegral”。例如:
import Data.List
roundDouble
:: Double
-> Int
-> Double
roundDouble x acc = fromIntegral (round $ x * 10 ** fromIntegral acc) / 10 ** fromIntegral acc
有没有更简单的写法? (我知道可能有更简单的方法来对数字进行四舍五入,如果有请告诉我!但是我主要感兴趣的是如何避免使用这么多“fromIntegrals”。)
谢谢,Ash
Whenever I write a function using doubles and integers, I find this problem where I am constantly having to use 'fromIntegral' everywhere in my function. For example:
import Data.List
roundDouble
:: Double
-> Int
-> Double
roundDouble x acc = fromIntegral (round $ x * 10 ** fromIntegral acc) / 10 ** fromIntegral acc
Is there an easier way of writing this? (I know there may be easier ways of rounding a number and if there are please let me know! However I am mainly interested in how to avoid using so many 'fromIntegrals'.)
Thanks, Ash
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有时我发现辅助函数很有用:
该辅助函数也可以编写为:
Where
on
is fromData.Function
。Sometimes I find a helper function useful:
That helper function can also be written:
Where
on
is fromData.Function
.您可以使用
^
代替**
。^
将任何 Integral 作为第二个参数,因此您无需对第二个操作数调用fromIntegral
。所以你的代码变成:roundDouble x acc = fromIntegral (round $ x * 10 ^ acc) / 10 ^ acc
其中只有一个
fromIntegral
。而您无法摆脱的那个,因为round
自然会返回一个 Integral,并且您无法对 Integral 执行非整数除法。You can use
^
instead of**
.^
takes any Integral as it's second argument, so you don't need to callfromIntegral
on the second operand. So your code becomes:roundDouble x acc = fromIntegral (round $ x * 10 ^ acc) / 10 ^ acc
Which has only one
fromIntegral
. And that one you can't get rid off asround
naturally returns an Integral and you can't perform non-integer division on an Integral.我对封送代码也有类似的问题,其中
fromIntegral
用于将 CInt 转换为 Int。我通常定义fI = fromIntegral
以使其更容易。您可能还需要为其提供显式类型签名或使用 -XNoMonomorphismRestriction。如果您需要进行大量数学运算,则可能需要查看 数值Prelude,它似乎在不同数字类型之间有更合理的关系。
I have a similar problem with marshaling code, where
fromIntegral
is used to convert CInt to Int. I usually definefI = fromIntegral
to make it easier. You may also need to give it an explicit type signature or use -XNoMonomorphismRestriction.If you're doing a lot of math, you may want to look at the Numeric Prelude, which seems to have much more sensible relations between different numeric types.
另一个想法,类似于luqui的。我与
fromIntegral
相关的大多数问题都与将Int
除以Double
或Double
除以Int 的必要性有关
。因此,这个(/.)
允许划分任意两个Real
类型,不一定相同,也不一定是Integral
类型,如 luqui 的解决方案中所示:示例:
它适用于任何两个
Real
,但我怀疑有理数除法和与Rational
之间的转换不是很有效。现在你的例子变成:
Another idea, similar to luqui's. Most of my problems with
fromIntegral
are related to necessity to divideInt
byDouble
orDouble
byInt
. So this(/.)
allows to divide any twoReal
types, not necessarily the same, an not necessarilyIntegral
types like in luqui's solution:Example:
It works for any two
Real
s, but I suspect that rational division and conversion to/fromRational
are not very effective.Now your example becomes: