aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/math/modulus.lux
blob: 3f976476a7305c1e592c1ec886f6890d735fea42 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
(.using
 [library
  [lux (.except)
   ["[0]" meta]
   [abstract
    [monad (.only do)]]
   [control
    ["[0]" try (.only Try)]
    ["[0]" exception (.only exception:)]
    [parser
     ["<[0]>" code]]]
   [macro
    [syntax (.only syntax)]
    ["[0]" code]]
   [math
    [number
     ["i" int]]]
   [type
    [primitive (.except)]]]])

(exception: .public zero_cannot_be_a_modulus)

(primitive .public (Modulus %)
  Int

  (def .public (modulus value)
    (Ex (_ %) (-> Int (Try (Modulus %))))
    (if (i.= +0 value)
      (exception.except ..zero_cannot_be_a_modulus [])
      {try.#Success (abstraction value)}))

  (def .public divisor
    (All (_ %) (-> (Modulus %) Int))
    (|>> representation))

  (def .public (= reference subject)
    (All (_ %r %s) (-> (Modulus %r) (Modulus %s) Bit))
    (i.= (representation reference)
         (representation subject)))

  (def .public (congruent? modulus reference subject)
    (All (_ %) (-> (Modulus %) Int Int Bit))
    (|> subject
        (i.- reference)
        (i.% (representation modulus))
        (i.= +0)))
  )

(def .public literal
  (syntax (_ [divisor <code>.int])
    (meta.lifted
     (do try.monad
       [_ (..modulus divisor)]
       (in (list (` ((~! try.trusted) (..modulus (~ (code.int divisor)))))))))))