Enums in Erlang

Our enum type ServerState has an underlying int type.

-type server_state() :: state_idle | state_connected | state_error | state_retrying.

-define(STATES, [state_idle, state_connected, state_error, state_retrying]).

-module(enums).
-export([main/0, transition/1, server_state_string/1]).

%% Define the possible states
-define(STATE_STR, #{state_idle => "idle",
                     state_connected => "connected",
                     state_error => "error",
                     state_retrying => "retrying"}).

%% Define the main function
main() ->
    Ns = transition(state_idle),
    io:format("~s~n", [server_state_string(Ns)]),
    Ns2 = transition(Ns),
    io:format("~s~n", [server_state_string(Ns2)]).

%% Function to handle state transitions
transition(State) ->
    case State of
        state_idle ->
            state_connected;
        state_connected ->
            state_idle;
        state_retrying ->
            state_idle;
        state_error ->
            state_error;
        _ ->
            erlang:error({unknown_state, State})
    end.

%% Function to return the string representation of a state
server_state_string(State) ->
    maps:get(State, ?STATE_STR).

To run the program, save the code in a file named enums.erl and then use the Erlang shell to compile and run it.

$ erlc enums.erl
$ erl -noshell -s enums main -s init stop
connected
idle

The transition function emulates a state transition for a server; it takes the existing state and returns a new state. The server_state_string function returns the string representation of each state, enabling us to print the current state in a human-readable format.