Nat.agda 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. {-# OPTIONS --no-termination-check #-}
  2. module Data.Nat where
  3. import Prelude
  4. import Data.Bool as Bool
  5. open Prelude
  6. open Bool
  7. data Nat : Set where
  8. zero : Nat
  9. suc : Nat -> Nat
  10. {-# BUILTIN NATURAL Nat #-}
  11. infix 40 _==_ _<_ _≤_ _>_ _≥_
  12. infixl 60 _+_ _-_
  13. infixl 70 _*_
  14. infixr 80 _^_
  15. infix 100 _!
  16. _+_ : Nat -> Nat -> Nat
  17. zero + m = m
  18. suc n + m = suc (n + m)
  19. _-_ : Nat -> Nat -> Nat
  20. zero - m = zero
  21. suc n - zero = suc n
  22. suc n - suc m = n - m
  23. _*_ : Nat -> Nat -> Nat
  24. zero * m = zero
  25. suc n * m = m + n * m
  26. _^_ : Nat -> Nat -> Nat
  27. n ^ zero = 1
  28. n ^ suc m = n * n ^ m
  29. _! : Nat -> Nat
  30. zero ! = 1
  31. suc n ! = suc n * n !
  32. {-# BUILTIN NATPLUS _+_ #-}
  33. {-# BUILTIN NATMINUS _-_ #-}
  34. {-# BUILTIN NATTIMES _*_ #-}
  35. _==_ : Nat -> Nat -> Bool
  36. zero == zero = true
  37. zero == suc _ = false
  38. suc _ == zero = false
  39. suc n == suc m = n == m
  40. _<_ : Nat -> Nat -> Bool
  41. n < zero = false
  42. zero < suc m = true
  43. suc n < suc m = n < m
  44. _≤_ : Nat -> Nat -> Bool
  45. n ≤ m = n < suc m
  46. _>_ = flip _<_
  47. _≥_ = flip _≤_
  48. {-# BUILTIN NATEQUALS _==_ #-}
  49. {-# BUILTIN NATLESS _<_ #-}
  50. divSucAux : Nat -> Nat -> Nat -> Nat -> Nat
  51. divSucAux k m zero j = k
  52. divSucAux k m (suc n) zero = divSucAux (suc k) m n m
  53. divSucAux k m (suc n) (suc j) = divSucAux k m n j
  54. modSucAux : Nat -> Nat -> Nat -> Nat -> Nat
  55. modSucAux k m zero j = k
  56. modSucAux k m (suc n) zero = modSucAux zero m n m
  57. modSucAux k m (suc n) (suc j) = modSucAux (suc k) m n j
  58. {-# BUILTIN NATDIVSUCAUX divSucAux #-}
  59. {-# BUILTIN NATMODSUCAUX modSucAux #-}
  60. div : Nat -> Nat -> Nat
  61. div n zero = zero
  62. div n (suc m) = divSucAux zero m n m
  63. mod : Nat -> Nat -> Nat
  64. mod n zero = zero
  65. mod n (suc m) = modSucAux zero m n m
  66. gcd : Nat -> Nat -> Nat
  67. gcd a 0 = a
  68. gcd a b = gcd b (mod a b)
  69. lcm : Nat -> Nat -> Nat
  70. lcm a b = div (a * b) (gcd a b)
  71. even : Nat -> Bool
  72. even n = mod n 2 == 0
  73. odd : Nat -> Bool
  74. odd n = mod n 2 == 1