Enums in Elixir

The translated Elixir code and corresponding explanations are below:

Our enum type ServerState has an underlying int type.

defmodule ServerState do
  @type t :: :idle | :connected | :error | :retrying
  @enums %{
    idle: "idle",
    connected: "connected",
    error: "error",
    retrying: "retrying"
  }

  def to_string(enum) do
    Map.get(@enums, enum)
  end
end

The possible values for ServerState are defined as atoms. The special mapping generates successive constant values automatically.

By implementing the to_string/1 function, values of ServerState can be printed out or converted to strings.

defmodule Main do
  def main do
    server_state = transition(:idle)
    IO.puts(ServerState.to_string(server_state))

    next_state = transition(server_state)
    IO.puts(ServerState.to_string(next_state))
  end

  defp transition(:idle), do: :connected
  defp transition(:connected), do: :idle
  defp transition(:error), do: :error
  defp transition(:retrying), do: :idle
  defp transition(state), do: raise("unknown state: #{ServerState.to_string(state)}")
end

Main.main()

The main/0 function prints the current state of a server, emulating a state transition system by taking the existing state and returning a new state.

To run the program, save the code in a file named server_state.exs and execute it using the Elixir command line:

$ elixir server_state.exs
connected
idle

Now that we can run and build basic Elixir programs, let’s learn more about the language.