はじめに
- @nezuq さんのPythonの集合演算を拝見しまして、私はぜひElixirでの話をまとめておこうとおもいました
- ElixirはElixir 1.10.4 (compiled with Erlang/OTP 23)を使いました
-
IEx
で試していきます
MapSet
iex> x = MapSet.new([1,2,3,4,5,6,1,1,1])
# MapSet<[1, 2, 3, 4, 5, 6]>
iex> y = MapSet.new([9,9,9,4,5,6,7,8,9])
# MapSet<[4, 5, 6, 7, 8, 9]>
MapSet.union/2
-
/
のうしろの数字は引数の数です - 和集合
iex> MapSet.union(x, y)
# MapSet<[1, 2, 3, 4, 5, 6, 7, 8, 9]>
MapSet.intersection/2
- 積集合
iex> MapSet.intersection(x, y)
# MapSet<[4, 5, 6]>
MapSet.difference/2
- 差集合
iex> MapSet.difference(x, y)
# MapSet<[1, 2, 3]>
XOR
iex> MapSet.union(x, y) |> MapSet.difference(MapSet.intersection(x, y))
# MapSet<[1, 2, 3, 7, 8, 9]>
- 関数は無いようでしたので、ベン図の要領で和集合から積集合を引きました
MapSet.subset?/2
- 第一引数のMapSetのすべてのメンバーが第二引数のMapSetのメンバーに含まれているかどうか
iex> x = MapSet.new([1,2,3])
# MapSet<[1, 2, 3]>
iex> y = MapSet.new([1,2,3,4,5])
# MapSet<[1, 2, 3, 4, 5]>
iex> MapSet.subset?(x, y)
true
MapSet.disjoint?/2
- 共通要素が無いかの判定
iex> x = MapSet.new([1,2,3])
# MapSet<[1, 2, 3]>
iex> y = MapSet.new([4,5,6])
# MapSet<[4, 5, 6]>
iex> MapSet.disjoint?(x, y)
true
iex> MapSet.disjoint?(MapSet.new([1, 2]), MapSet.new([2, 3]))
false