blob: ae79ff1e12461db978a04a191888843fa1f5ed03 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
local class = require'r.class'
local Set = class()
function Set.make(cls, items) return setmetatable({_=items or {}},cls) end
function Set.has(self, item) return self._[item] end
function Set.add(self, item) self._[item] = true end
function Set.del(self, item) self._[item] = nil end
function Set.each(self) return pairs(self._) end
function Set.one(self) return next(self._) end
function Set.__len(self) local i = 0 for k in self:each() do i=i+1 end return i end
function Set.copy(self) local o={} for k in self:each() do o[k]=true end return Set(o) end
function Set.union(self,other) local o=self:copy() if other == nil then return o end
for k in other:each() do o:add(k) end return o end
function Set.insect(self,other) local o=self:copy() if other == nil then return o end
for k in o:each() do if not other:has(k) then o:del(k) end end return o end
function Set.diff(self,other) local o,p = self:copy(), other:copy()
for k in self:each() do p:del(k) end
for k in other:each() do o:del(k) end
return o,p end
return Set
|