aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/data/collection/set.lux
blob: 3507442c34487d012db69bb09454c93167904a63 (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
(.using
 [library
  [lux {"-" has list}
   [abstract
    [equivalence {"+" Equivalence}]
    [hash {"+" Hash}]
    [predicate {"+" Predicate}]
    [monoid {"+" Monoid}]]
   [data
    [collection
     ["[0]" list ("[1]#[0]" mix)]]]
   [macro
    ["^" pattern]]
   [math
    [number
     ["n" nat]]]]]
 ["[0]" // "_"
  ["[1]" dictionary {"+" Dictionary}]])

(type: .public (Set a)
  (Dictionary a Any))

(def: .public member_hash
  (All (_ a) (-> (Set a) (Hash a)))
  //.key_hash)

(def: .public empty
  (All (_ a) (-> (Hash a) (Set a)))
  //.empty)

(def: .public size
  (All (_ a) (-> (Set a) Nat))
  //.size)

(def: .public (has elem set)
  (All (_ a) (-> a (Set a) (Set a)))
  (|> set (//.has elem [])))

(def: .public lacks
  (All (_ a) (-> a (Set a) (Set a)))
  //.lacks)

(def: .public member?
  (All (_ a) (-> (Set a) a Bit))
  //.key?)

(def: .public list
  (All (_ a) (-> (Set a) (List a)))
  //.keys)

(def: .public union
  (All (_ a) (-> (Set a) (Set a) (Set a)))
  //.composite)

(def: .public (difference sub base)
  (All (_ a) (-> (Set a) (Set a) (Set a)))
  (list#mix ..lacks base (..list sub)))

(def: .public (intersection filter base)
  (All (_ a) (-> (Set a) (Set a) (Set a)))
  (//.sub (//.keys filter)
          base))

(implementation: .public equivalence
  (All (_ a) (Equivalence (Set a)))
  
  (def: (= (^.let reference [hash _]) sample)
    (and (n.= (..size reference)
              (..size sample))
         (list.every? (..member? reference)
                      (..list sample)))))

(implementation: .public hash
  (All (_ a) (Hash (Set a)))
  
  (def: &equivalence ..equivalence)
  
  (def: (hash set)
    (|> set
        ..list
        (# (list.hash (..member_hash set)) hash))))

(implementation: .public (monoid hash)
  (All (_ a) (-> (Hash a) (Monoid (Set a))))

  (def: identity (..empty hash))
  (def: composite ..union))

(def: .public empty?
  (All (_ a) (-> (Set a) Bit))
  (|>> ..size (n.= 0)))

(def: .public (of_list hash elements)
  (All (_ a) (-> (Hash a) (List a) (Set a)))
  (list#mix ..has (..empty hash) elements))

(def: .public (sub? super sub)
  (All (_ a) (-> (Set a) (Set a) Bit))
  (list.every? (..member? super) (..list sub)))

(def: .public (super? sub super)
  (All (_ a) (-> (Set a) (Set a) Bit))
  (..sub? super sub))

(def: .public predicate
  (All (_ a) (-> (Set a) (Predicate a)))
  ..member?)