aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/data/collection/set.lux
blob: e3bf42911acec88cc3af258dc81766b43d508138 (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
108
109
110
(.require
 [library
  [lux (.except has list)
   [abstract
    [equivalence (.only Equivalence)]
    [hash (.only Hash)]
    [monoid (.only Monoid)]]
   [control
    [function
     [predicate (.only Predicate)]]]
   [data
    [collection
     ["[0]" list (.use "[1]#[0]" mix)]]]
   [math
    [number
     ["n" nat]]]
   [meta
    [macro
     ["^" pattern]]]]]
 ["[0]" //
  ["[1]" dictionary (.only 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))

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

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

(def .public (monoid hash)
  (All (_ a) (-> (Hash a) (Monoid (Set a))))
  (implementation
   (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?)