|
1 | 1 | module Data.Rational |
2 | 2 | ( Rational |
| 3 | + , (%) |
3 | 4 | , toNumber |
4 | 5 | , fromInt |
5 | | - , module Data.Ratio |
| 6 | + , fromBigInt |
| 7 | + , numerator |
| 8 | + , denominator |
| 9 | + , class ToRational |
| 10 | + , toRational |
6 | 11 | ) where |
7 | 12 |
|
8 | 13 | import Prelude |
9 | 14 |
|
10 | 15 | import Data.Int as Int |
11 | 16 | import Data.Ratio (Ratio, denominator, numerator, (%)) |
| 17 | +import Data.Ratio as Ratio |
| 18 | +import JS.BigInt (BigInt) |
| 19 | +import JS.BigInt as BigInt |
12 | 20 |
|
13 | | -type Rational = Ratio Int |
| 21 | +newtype Rational = Rational (Ratio.Ratio BigInt) |
| 22 | + |
| 23 | +derive newtype instance Eq Rational |
| 24 | +derive newtype instance Ord Rational |
| 25 | +derive newtype instance Show Rational |
| 26 | +derive newtype instance Semiring Rational |
| 27 | +derive newtype instance Ring Rational |
| 28 | +derive newtype instance CommutativeRing Rational |
| 29 | +derive newtype instance EuclideanRing Rational |
| 30 | +derive newtype instance DivisionRing Rational |
14 | 31 |
|
15 | 32 | toNumber :: Rational -> Number |
16 | | -toNumber x = Int.toNumber (numerator x) / Int.toNumber (denominator x) |
| 33 | +toNumber (Rational x) = BigInt.toNumber (Ratio.numerator x) / BigInt.toNumber (Ratio.denominator x) |
17 | 34 |
|
18 | 35 | fromInt :: Int -> Rational |
19 | | -fromInt i = i % 1 |
| 36 | +fromInt i = Rational $ Ratio.reduce (BigInt.fromInt i) (BigInt.fromInt 1) |
| 37 | + |
| 38 | +fromBigInt :: BigInt -> Rational |
| 39 | +fromBigInt i = Rational $ Ratio.reduce i (BigInt.fromInt 1) |
| 40 | + |
| 41 | +numerator :: Rational -> BigInt |
| 42 | +numerator (Rational x) = Ratio.numerator x |
| 43 | + |
| 44 | +denominator :: Rational -> BigInt |
| 45 | +denominator (Rational x) = Ratio.denominator x |
| 46 | + |
| 47 | +class |
| 48 | + ToRational a |
| 49 | + where |
| 50 | + toRational :: a -> a -> Rational |
| 51 | + |
| 52 | +instance ToRational Int |
| 53 | + where |
| 54 | + toRational a b = Rational $ Ratio.reduce (BigInt.fromInt a) (BigInt.fromInt b) |
| 55 | + |
| 56 | +instance ToRational BigInt |
| 57 | + where |
| 58 | + toRational a b = Rational $ Ratio.reduce a b |
| 59 | + |
| 60 | +infixl 7 toRational as % |
0 commit comments