You might use Enum.reduce/3 in the following way (untested, but it should work):
Enum.reduce(sets, [], fn set, sets ->
case Enum.split_with(sets, &MapSet.disjoint?(&1, set)) do
{_, []} -> # not a single join, totally alien, appending
[set | sets]
{disjoined, joined} -> # ⇓⇓⇓ here is a trick ⇓⇓⇓
[Enum.reduce(joined, set, &MapSet.union/2) | disjoined]
end
end)
The only interesting thing here is that once we discovered all the sets joined the tested one, all of them are to be joined.






















