-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset.lua
92 lines (83 loc) · 1.93 KB
/
set.lua
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
local function tostringstack(a, ...)
if a == nil then return end
return tostring(a), tostringstack(...)
end
local set_mt = {
__sub = function(a, b)
local c = set()
for k,v in pairs(a) do
if b[k] == nil then
c[k] = true
end
end
return c
end,
__add = function(a, b)
local c = set()
for k,v in pairs(a) do
c[k] = true
end
for k,v in pairs(b) do
c[k] = true
end
return c
end,
__eq = function(a, b)
for k,v in pairs(a) do
if not b[k] then return false end
end
for k,v in pairs(b) do
if not a[k] then return false end
end
return true
end,
__tostring = function(self)
local l = {}
for k,v in pairs(self) do
table.insert(l, k)
end
table.sort(l)
return 'set(' .. table.concat({tostringstack(unpack(l))}, ', ') .. ')'
end,
__len = function(self)
local c = 0
for k,v in pairs(self) do
c = c + 1
end
return c
end,
__index = {
tolist = function(self)
local list = {}
local c = 1
for k,v in pairs(self) do
list[c] = k
c = c + 1
end
return list
end,
union = function(self, other)
for k,v in pairs(other) do
self[k] = true
end
end,
intersect = function(self, other)
local r = set()
for k,v in pairs(self, other) do
if other[k] then
r[k] = true
end
end
return r
end,
},
}
function set(list)
local t = {}
if list then
for k,v in ipairs(list) do
t[v] = true
end
end
return setmetatable(t, set_mt)
end