aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/data/coll/set.lux
blob: 06953ef23e7d6edf3560a32e7cfd082d4a195646 (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
(;module:
  lux
  (lux (control functor
                applicative
                monad
                [eq #+ Eq]
                [hash #*])
       (data (coll [dict]
                   [list "List/" Fold<List> Functor<List>]))))

## [Types]
(type: #export (Set a)
  (dict;Dict a a))

## [Values]
(def: #export (new Hash<a>)
  (All [a] (-> (Hash a) (Set a)))
  (dict;new Hash<a>))

(def: #export (add elem set)
  (All [a] (-> a (Set a) (Set a)))
  (dict;put elem elem set))

(def: #export (remove elem set)
  (All [a] (-> a (Set a) (Set a)))
  (dict;remove elem set))

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

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

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

(def: #export (union xs yx)
  (All [a] (-> (Set a) (Set a) (Set a)))
  (dict;merge xs 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)))
  (dict;select (dict;keys filter) base))

(def: #export (size set)
  (All [a] (-> (Set a) Nat))
  (dict;size set))

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

(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))

## [Structures]
(struct: #export Eq<Set> (All [a] (Eq (Set a)))
  (def: (= (^@ test [Hash<a> _]) subject)
    (:: (list;Eq<List> (get@ #hash;eq Hash<a>)) = (to-list test) (to-list subject))))

(struct: #export Hash<Set> (All [a] (Hash (Set a)))
  (def: eq Eq<Set>)
  
  (def: (hash (^@ set [Hash<a> _]))
    (List/fold (function [elem acc] (n.+ (:: Hash<a> hash elem) acc))
               +0
               (to-list set))))