aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/data/collection/set.lux
blob: 5fa774e9e1fd741030ebf1a15ef052a2eecd2891 (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
(.module:
  [lux #*
   [control
    [equivalence (#+ Equivalence)]
    [hash (#+ Hash)]]
   [data
    [collection
     ["dict" dictionary (#+ Dictionary)]
     [list ("list/" Fold<List>)]]]
   [type abstract]])

(abstract: #export (Set a)
  {}
  
  (Dictionary a a)

  (def: #export new
    (All [a] (-> (Hash a) (Set a)))
    (|>> dict.new :abstraction))

  (def: #export size
    (All [a] (-> (Set a) Nat))
    (|>> :representation dict.size))

  (def: #export (add elem set)
    (All [a] (-> a (Set a) (Set a)))
    (|> set :representation (dict.put elem elem) :abstraction))

  (def: #export (remove elem set)
    (All [a] (-> a (Set a) (Set a)))
    (|> set :representation (dict.remove elem) :abstraction))

  (def: #export (member? set elem)
    (All [a] (-> (Set a) a Bool))
    (|> set :representation (dict.contains? elem)))

  (def: #export to-list
    (All [a] (-> (Set a) (List a)))
    (|>> :representation dict.keys))

  (def: #export (union xs yx)
    (All [a] (-> (Set a) (Set a) (Set a)))
    (:abstraction (dict.merge (:representation xs) (:representation yx))))

  (def: #export (difference sub base)
    (All [a] (-> (Set a) (Set a) (Set a)))
    (list/fold ..remove base (..to-list sub)))

  (def: #export (intersection filter base)
    (All [a] (-> (Set a) (Set a) (Set a)))
    (:abstraction (dict.select (dict.keys (:representation filter))
                               (:representation base))))

  (structure: #export Equivalence<Set> (All [a] (Equivalence (Set a)))
    (def: (= reference sample)
      (let [[Hash<a> _] (:representation reference)]
        (:: (list.Equivalence<List> (get@ #hash.eq Hash<a>)) =
            (..to-list reference) (..to-list sample)))))

  (structure: #export Hash<Set> (All [a] (Hash (Set a)))
    (def: eq ..Equivalence<Set>)
    
    (def: (hash set)
      (let [[Hash<a> _] (:representation set)]
        (list/fold (function (_ elem acc) (n/+ (:: Hash<a> hash elem) acc))
                   +0
                   (..to-list set)))))
  )

(def: #export empty?
  (All [a] (-> (Set a) Bool))
  (|>> ..size (n/= +0)))

(def: #export (from-list Hash<a> xs)
  (All [a] (-> (Hash a) (List a) (Set a)))
  (list/fold ..add (..new Hash<a>) xs))

(def: #export (sub? super sub)
  (All [a] (-> (Set a) (Set a) Bool))
  (list.every? (..member? super) (..to-list sub)))

(def: #export (super? sub super)
  (All [a] (-> (Set a) (Set a) Bool))
  (sub? super sub))