I want to create a enum in Elixir. Is it possible? By enum I mean enums from C/C++ or Ruby or in many other languages. I'm aware of the Enum
module but that's just a module -- a container for functions basically.
If I understand you correctly, you are looking for a way to use enumeration in Elixir. You can do this with an instance of a Map using :atoms as keys.
weekdays = [:monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday]
|> Enum.with_index
|> Map.new
Or a bit more manually
weekdays = %{
monday: 0,
tuesday: 1,
wednesday: 2,
thursday: 3,
friday: 4,
saturday: 5,
sunday: 6}
If you're using :atoms as keys, the short-hand access syntax is:
iex> weekdays.monday
0
iex> weekdays.friday
4
But usually using atoms such as :error or :ok doesn't require you to do these declarations.
I dont know if it is a good idea, but you can create a module (CustomEnum) where you define functions as Enums.
defmodule CustomEnum do
def monday, do: 0
def tuesday,do: 1
end
Then, you can call CustomEnum.monday and get value 0
Write all this functions could be boring, so you can create a list of tuples and dynamically create your function for each item. EX>
defmodule CustomWeekDaysEnum do
weekdays = [
monday: {0},
tuesday: {1},
wednesday: {2},
thursday: {3}
....
]
#creating functions dynamically
for{function_name, {value} <- weekdays do
def unquote(function_name)(), do: unquote(value)
end
end
Now you call CustomWeekDaysEnum.wednesday and get 2, or CustomWeekDaysEnum.thursday and get 3.
And now, if you need a new Enum item, just put it in weekdays List and your function will be created at compile time.
weekdays is a list of tuples, so your enums can have multiple values inside. you just have to change unquoted def to return the tuple or just specific values
Just remember: Functions dynamically created are cool but your code may become harder to read.
You can find more about it in Saša Jurić post
The Erlangelist
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With