Enums in Wolfram Language

Based on the input, the target language is Wolfram Language. Here is the equivalent translation to Wolfram Language:


Enumerated types (enums) are a special case of sum types. An enum is a type that has a fixed number of possible values, each with a distinct name. Wolfram Language doesn’t have an enum type as a distinct language feature, but enums are simple to implement using existing language idioms.

Our enum type ServerState has an underlying int type.

states = {"StateIdle" -> 0, "StateConnected" -> 1, "StateError" -> 2, "StateRetrying" -> 3};

The possible values for ServerState are defined as constants.

By implementing a string representation, values of ServerState can be printed out or converted to strings.

stateName = <|0 -> "idle", 1 -> "connected", 2 -> "error", 3 -> "retrying"|>;
stringify[state_] := stateName[state];

If we have a value of type int, we cannot pass it directly as an enum value; this provides some degree of type safety for enums.

transition[state_Integer] := 
  Switch[state, 
    states["StateIdle"], stateName[0],
    states["StateConnected"], states["StateIdle"],
    states["StateRetrying"], states["StateIdle"],
    states["StateError"], states["StateError"],
    _, "unknown state: " <> ToString[state]
  ]

main := Module[{ns, ns2},
  ns = transition[states["StateIdle"]];
  Print[ns];
  ns2 = transition[states["StateConnected"]];
  Print[ns2];
]

main[]

transition emulates a state transition for a server; it takes the existing state and returns a new state.

To run this, simply evaluate the Wolfram Language code segment.

$ wolfram -script enums.wl
connected
idle

Now that we understand how to implement enums in Wolfram Language, let’s learn more about the language.


Next example: Struct Embedding.