Rational.agda 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. {-# OPTIONS --no-termination-check #-}
  2. module Data.Rational where
  3. import Data.Bool as Bool
  4. import Data.Nat as Nat
  5. import Data.Integer as Int
  6. open Int renaming
  7. ( _*_ to _*'_
  8. ; _+_ to _+'_
  9. ; -_ to -'_
  10. ; _-_ to _-'_
  11. ; !_! to !_!'
  12. ; _==_ to _=='_
  13. ; _≤_ to _≤'_
  14. ; _≥_ to _≥'_
  15. ; _>_ to _>'_
  16. ; _<_ to _<'_
  17. )
  18. open Nat using (Nat; zero; suc)
  19. open Bool
  20. infix 40 _==_ _<_ _>_ _≤_ _≥_
  21. infixl 60 _+_ _-_
  22. infixl 70 _%'_ _%_ _/_ _*_
  23. infixr 80 _^_
  24. infix 90 -_
  25. data Rational : Set where
  26. _%'_ : Int -> Int -> Rational
  27. numerator : Rational -> Int
  28. numerator (n %' d) = n
  29. denominator : Rational -> Int
  30. denominator (n %' d) = d
  31. _%_ : Int -> Int -> Rational
  32. neg n % neg m = pos (suc n) % pos (suc m)
  33. pos 0 % neg m = pos 0 %' pos 1
  34. pos (suc n) % neg m = neg n % pos (suc m)
  35. x % y = div x z %' div y z
  36. where
  37. z = gcd x y
  38. fromInt : Int -> Rational
  39. fromInt x = x %' pos 1
  40. fromNat : Nat -> Rational
  41. fromNat x = fromInt (pos x)
  42. _+_ : Rational -> Rational -> Rational
  43. (a %' b) + (c %' d) = (a *' d +' c *' b) % (b *' d)
  44. -_ : Rational -> Rational
  45. - (a %' b) = -' a %' b
  46. _-_ : Rational -> Rational -> Rational
  47. a - b = a + (- b)
  48. _/_ : Rational -> Rational -> Rational
  49. (a %' b) / (c %' d) = (a *' d) % (b *' c)
  50. _*_ : Rational -> Rational -> Rational
  51. (a %' b) * (c %' d) = (a *' c) % (b *' d)
  52. recip : Rational -> Rational
  53. recip (a %' b) = b %' a
  54. _^_ : Rational -> Int -> Rational
  55. q ^ neg n = recip q ^ pos (suc n)
  56. q ^ pos zero = fromNat 1
  57. q ^ pos (suc n) = q * q ^ pos n
  58. !_! : Rational -> Rational
  59. ! a %' b ! = pos ! a !' %' pos ! b !'
  60. round : Rational -> Int
  61. round (a %' b) = div (a +' div b (pos 2)) b
  62. _==_ : Rational -> Rational -> Bool
  63. (a %' b) == (c %' d) = a *' d ==' b *' c
  64. _<_ : Rational -> Rational -> Bool
  65. (a %' b) < (c %' d) = a *' d <' b *' c
  66. _>_ : Rational -> Rational -> Bool
  67. (a %' b) > (c %' d) = a *' d >' b *' c
  68. _≤_ : Rational -> Rational -> Bool
  69. (a %' b) ≤ (c %' d) = a *' d ≤' b *' c
  70. _≥_ : Rational -> Rational -> Bool
  71. (a %' b) ≥ (c %' d) = a *' d ≥' b *' c
  72. max : Rational -> Rational -> Rational
  73. max a b = if a < b then b else a
  74. min : Rational -> Rational -> Rational
  75. min a b = if a < b then a else b