aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/data/struct/set.lux
blob: 085c0f0472f84bd84c2626e81cbf33d5481dce84 (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
##  Copyright (c) Eduardo Julian. All rights reserved.
##  This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
##  If a copy of the MPL was not distributed with this file,
##  You can obtain one at http://mozilla.org/MPL/2.0/.

(;module:
  lux
  (lux (control functor
                applicative
                monad
                eq
                [hash #*])
       (data (struct [dict]
                     [list "List/" Fold<List> Functor<List>]))
       (codata function)))

## [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 (union xs yx)
  (All [a] (-> (Set a) (Set a) (Set a)))
  (dict;merge xs yx))

(def: #export (difference subs base)
  (All [a] (-> (Set a) (Set a) (Set a)))
  (List/fold remove base (dict;keys subs)))

(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))
  (=+ +0 (dict;size 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 (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 (lambda [elem acc] (++ (:: Hash<a> hash elem) acc))
               +0
               (to-list set))))