luaコレクション操作

1073 ワード

local Set = {}
local mt = {}
function Set.new(t)
  local set = {}
  setmetatable(set, mt)
  for k,v in pairs(t) do
    set[v] = true
  end
  return set
end

function Set.union(a,b)
  local set = Set.new{}
  for k in pairs(a) do
    set[k] = true
  end
  for k in pairs(b) do
    set[k] = true
  end
  return set
end

function Set.tostring(set)
 local l = {}
 for e in pairs(set) do
 l[#l+1] = e
 end
 return "{"..table.concat(l,",").."}"
end

function Set.print(s)
 print(Set.tostring(s))
end
 
function Set.intersection(a,b)
  local set = Set.new{}
  for k in pairs(a) do
    if b[k] then
      set[k] = true
    end
  end
  return set
end

function Set.complementary(a,b)
  local set = Set.new{}
  for k in pairs(a) do
    if not b[k] then
      set[k] = true
    end
  end
  return set
end

mt.__add = Set.union
mt.__mul = Set.intersection 
mt.__sub = Set.complementary

local a = Set.new{2,3,4,5}
local b = Set.new{1,6,3}

local s = a - b

Set.print(s)

local s = a + b

Set.print(s)

local s = a * b

Set.print(s)