From c536f4054a1d06bd2cf0d1aaa34dc4c55f56551f Mon Sep 17 00:00:00 2001 From: rebecca Date: Sun, 20 Sep 2026 11:40:25 +0100 Subject: add set --- set.lua | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 set.lua (limited to 'set.lua') 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 + -- cgit v1.2.3