summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--set.lua20
1 files changed, 20 insertions, 0 deletions
diff --git a/set.lua b/set.lua
new file mode 100644
index 0000000..ae79ff1
--- /dev/null
+++ b/set.lua
@@ -0,0 +1,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
+