# Looping over Sets using Recursion

**URL:** <https://forum.elixirforum.com/t/looping-over-sets-using-recursion/43721>\
**Category:** Questions\
**Tags:** learning-elixir\
**Created:** [November 9, 2021, 11:03am UTC](https://forum.elixirforum.com/t/looping-over-sets-using-recursion/43721 "2021-11-09T11:03:44Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![stefanluptak](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/stefanluptak/32/34398_2.png) [@stefanluptak](https://forum.elixirforum.com/u/stefanluptak)\
**Post date:** [November 9, 2021, 11:58am UTC](https://forum.elixirforum.com/t/looping-over-sets-using-recursion/43721/4 "2021-11-09T11:58:11Z")

</div>

Sets ([MapSet](https://hexdocs.pm/elixir/1.12.3/MapSet.html#content)) in Elixir are implemented using [Maps](https://hexdocs.pm/elixir/1.12.3/Map.html#content).  
When you do this:

```elixir
[1, 2, 3]
|> MapSet.new()
|> Map.to_list()

```

you will see, that the result is this

```elixir
[__struct__ : MapSet, map: %{1 => [], 2 => [], 3 => []}, version: 2]

```

That means, that the MapSet is just a map with some special keys (similar to Struct). That means you’re able to pattern match on the `map` key of the MapSet map.

So some naive implementation could be something like this:

```elixir
defmodule RecursiveMapSet do
  def sum(%{map: set}) when map_size(set) == 0 do
    0
  end
  
  def sum(set) do
    {[element], rest_of_the_set} = Enum.split(set, 1)
    element + sum(MapSet.new(rest_of_the_set))
  end
end
  
set = MapSet.new([1, 2, 3])
RecursiveMapSet.sum(set) # 6

```

Anyway, I feel like ergonomics of lists are far better than MapSet, so I would just convert it to list, do the recursive work and then convert back to MapSet.

**UPDATE:** As @hauleth mentioned below, the fact that MapSet is just a Map is an implementation detail, that you should not rely on, because it can change in the future.

---

_[View the full topic](https://forum.elixirforum.com/t/looping-over-sets-using-recursion/43721)._
