-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSet.lua
More file actions
58 lines (50 loc) · 1.03 KB
/
Set.lua
File metadata and controls
58 lines (50 loc) · 1.03 KB
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
local Set = {}
local mt = {}
function Set.new(l)
local set = {}
setmetatable(set, mt)
for _, v in ipairs(l) do set[v] = true end
return set
end
function Set.union(a, b)
local res = Set.new{}
for k in pairs(a) do res[k] = true end
for k in pairs(b) do res[k] = true end
return res
end
function Set.intersection(a, b)
local res = Set.new{}
for k in pairs(a) do
res[k] = b[k]
end
return res
end
function Set.diference(a, b)
local res = Set.new{}
for k in pairs(a) do
if not b[k] then
res[k] = a[k]
end
end
return res
end
function Set.length(set)
local count = 0
for _ in pairs(set) do
count = count + 1
end
return count
end
function Set.tostring(set)
local l = {}
for e in pairs(set) do
l[#l + 1] = tostring(e)
end
return "{" .. table.concat(l, ", ") .. "}"
end
mt.__add = Set.union
mt.__sub = Set.diference
mt.__mul = Set.intersection
mt.__len = Set.length
mt.__tostring = Set.tostring
return Set