SimpleEnum - Use Enumerations in Elixir

Thanks for the question.

I’ve never used ex_const so my answer probably won’t be complete but here are the main differences I noticed.

First of all, you must know that when writing SimpleEnum, I got a lot of inspiration from how Enumerations work in C++. This explains some of my design choices like the fact that it is impossible to have 2 times the same key in an Enum.

Difference 1: with ex_const, an Enum can have duplicates keys and values.
This is a valid code :

enum type do
    key1 	0
    key1	1
    key1	1
end

iex> Enums.type(:key1)
0

Here SimpleEnum will raise an exception at compile time:

defenum :type, [key1: 0, key1: 1, key1: 1]
# ** (CompileError) tests.exs:13: duplicate key :key1 found in enum Enums.type

Difference 2: ex_const does not support lists of keywords for creating Enums
With SimpleEnum, you can do

defenum :type, [:key1, :key2, :key3]

iex> type(:__enumerators__)
[key1: 0, key2: 1, key3: 2]

Difference 3: ex_const can be used at compile time to get a value from a key but not the opposite.

enum type do
    key1 	0
end

# Valid: when x == 0
def test(x) when x == Enums.type(:key1), do: x
# Raise
def test(x) when x == Enums.type(0), do: x
# Raise
def test(x) when x == Enums.from_type(0), do: x

With SimpleEnum you can do

defenum :type, [:key1]

# Valid: when x == 0
def test(x) when x == Enums.type(:key1), do: x
# Also valid: when x == :key1
def test(x) when x == Enums.type(0), do: x

Difference 4: ex_const does not seem to have any introspection helper.

5 Likes