Using numbers to do arithmetic with fractions in PureScript may yield surprising results:
> 0.1 + 0.2
0.30000000000000004
The same can be expressed accurately with Rational using the (%) operator:
> import Data.Rational
> (1 % 10) + (2 % 10)
3 % 10
You can turn a Rational to a Number:
> toNumber (3 % 10)
0.3
Install rationals with Spago:
spago install rationals
# Or with Bower
bower install purescript-rationalsRational is just a type alias for Ratio Int and you might want to use
Ratio with other than Int. The type you choose must however be an EuclideanRing.
For example, one limitation with Rational is that it can easily overflow
the 32-bit PureScript Int. You can get around this problem by using
BigInt.
> import Data.Ratio ((%), reduce)
> import Data.BigInt (fromInt, fromString)
> :type fromInt 1 % fromInt 3
Ratio BigInt
> reduce <$> fromString "10" <*> fromString "857981209301293808359384092830482"
(Just fromString "5" % fromString "428990604650646904179692046415241")
rationals documentation is stored in a few places:
- Module documentation is published on Pursuit.
- Usage examples can be found in the test suite.
If you get stuck, there are several ways to get help:
- Open an issue if you have encountered a bug or problem.
- Ask general questions on the PureScript Discourse forum or the PureScript Discord chat.
You can contribute to rationals in several ways:
-
If you encounter a problem or have a question, please open an issue. We'll do our best to work with you to resolve or answer it.
-
If you would like to contribute code, tests, or documentation, please read the contributor guide. It's a short, helpful introduction to contributing to this library, including development instructions.
-
If you have written a library, tutorial, guide, or other resource based on this package, please share it on the PureScript Discourse! Writing libraries and learning resources are a great way to help this library succeed.