aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/data/collection/set/ordered.lux
blob: e69dba5fed8ccc82a10eec2e62d73e7b6c60177f (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
(.module:
  [library
   [lux (#- list)
    [abstract
     [equivalence (#+ Equivalence)]
     [order (#+ Order)]]
    [data
     [collection
      ["." list ("#\." fold)]
      [dictionary
       ["/" ordered]]]]
    [type
     abstract]]])

(abstract: .public (Set a)
  {#.doc (example "A set with ordered entries.")}

  (/.Dictionary a a)

  (def: .public empty
    (All [a] (-> (Order a) (Set a)))
    (|>> /.empty :abstraction))

  (def: .public (member? set elem)
    (All [a] (-> (Set a) a Bit))
    (/.key? (:representation set) elem))

  (template [<type> <name> <alias>]
    [(def: .public <name>
       (All [a] (-> (Set a) <type>))
       (|>> :representation <alias>))]

    [(Maybe a) min /.min]
    [(Maybe a) max /.max]
    [Nat size  /.size]
    [Bit empty? /.empty?]
    )

  (def: .public (add elem set)
    (All [a] (-> a (Set a) (Set a)))
    (|> set :representation (/.put elem elem) :abstraction))

  (def: .public (remove elem set)
    (All [a] (-> a (Set a) (Set a)))
    (|> set :representation (/.remove elem) :abstraction))

  (def: .public list
    (All [a] (-> (Set a) (List a)))
    (|>> :representation /.keys))

  (def: .public (of_list &order list)
    (All [a] (-> (Order a) (List a) (Set a)))
    (list\fold add (..empty &order) list))

  (def: .public (union left right)
    (All [a] (-> (Set a) (Set a) (Set a)))
    (list\fold ..add right (..list left)))

  (def: .public (intersection left right)
    (All [a] (-> (Set a) (Set a) (Set a)))
    (|> (..list right)
        (list.only (..member? left))
        (..of_list (get@ #/.&order (:representation right)))))

  (def: .public (difference param subject)
    (All [a] (-> (Set a) (Set a) (Set a)))
    (|> (..list subject)
        (list.only (|>> (..member? param) not))
        (..of_list (get@ #/.&order (:representation subject)))))

  (implementation: .public equivalence
    (All [a] (Equivalence (Set a)))
    
    (def: (= reference sample)
      (\ (list.equivalence (\ (:representation reference) &equivalence))
         = (..list reference) (..list sample))))
  )

(def: .public (sub? super sub)
  {#.doc (example "Is 'sub' a sub-set of 'super'?")}
  (All [a] (-> (Set a) (Set a) Bit))
  (|> sub
      ..list
      (list.every? (..member? super))))

(def: .public (super? sub super)
  {#.doc (example "Is 'super' a super-set of 'sub'?")}
  (All [a] (-> (Set a) (Set a) Bit))
  (sub? super sub))