-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex20.2.lua
59 lines (55 loc) · 1.17 KB
/
ex20.2.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
local Set = {}
local mt = {}
-- create a new set with the values of a given list
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.diff (a, b)
local res = Set.new{}
for k in pairs(a) do
if not b[k] then
res[k] = true
end
end
return res
end
-- presents a set as a string
function Set.tostring (set)
local l = {}
-- list to put all elements from the set
for e in pairs(set) do
l[#l + 1] = tostring(e)
end
return "{" .. table.concat(l, ", ") .. "}"
end
function Set.len (set)
local count = 0
for _ in pairs(set) do
count = count + 1
end
return count
end
mt.__add = Set.union
mt.__mul = Set.intersection
mt.__sub = Set.diff
mt.__tostring = Set.tostring
mt.__len = Set.len
local s1 = Set.new({10, 20, 30})
print(#s1)
-- return Set