如何在Haskell中将小数部分解析为Rational? [英] How to parse a decimal fraction into Rational in Haskell?

查看:142
本文介绍了如何在Haskell中将小数部分解析为Rational?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我参加了编程竞赛其中一个问题的输入数据包含一个十进制格式的小数: 0.75 是一个例子。



解析成 Double 是微不足道的(我可以使用 read ),但精度的损失是痛苦的。对 Double 比较(我不是)来说,需要非常小心,这看起来是多余的,因为它具有 Rational 数据键入Haskell。



试图使用它时,我发现 read a Rational 必须提供以下格式的字符串: numerator%denominator ,显然我没有。



所以,问题是:

将分数的十进制表示解析成最简单的方法是什么 Rational



也应该考虑外部依赖的数量,你需要的函数是 Numeric.readFloat

code>:

 数值Data.Ratio> fst。 head $ readFloat0.75:: Rational 
3%4


I've been participating in a programming contest and one of the problems' input data included a fractional number in a decimal format: 0.75 is one example.

Parsing that into Double is trivial (I can use read for that), but the loss of precision is painful. One needs to be very careful with Double comparisons (I wasn't), which seems redundant since one has Rational data type in Haskell.

When trying to use that, I've discovered that to read a Rational one has to provide a string in the following format: numerator % denominator, which I, obviously, do not have.

So, the question is:

What is the easiest way to parse a decimal representation of a fraction into Rational?

The number of external dependencies should be taken into consideration too, since I can't install additional libraries into the online judge.

解决方案

The function you want is Numeric.readFloat:

Numeric Data.Ratio> fst . head $ readFloat "0.75" :: Rational
3 % 4

这篇关于如何在Haskell中将小数部分解析为Rational?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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