Enums in Miranda

Based on the input, the target language specified is “Python”. Here’s the translated code example in Markdown format suitable for Hugo.


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. Go doesn’t have an enum type as a distinct language feature, but enums are simple to implement using existing language idioms.

Example

Our enum type ServerState uses the int type as an underlying type.

from enum import Enum

class ServerState(Enum):
    Idle = 0
    Connected = 1
    Error = 2
    Retrying = 3

The possible values for ServerState are defined as constants. The Enum class in Python ensures that each value is unique and iterable.

By implementing the __str__ method, values of ServerState can be printed out or converted to strings.

class ServerState(Enum):
    Idle = 0
    Connected = 1
    Error = 2
    Retrying = 3

    def __str__(self):
        return self.name.lower()

state_name = {
    ServerState.Idle: "idle",
    ServerState.Connected: "connected",
    ServerState.Error: "error",
    ServerState.Retrying: "retrying"
}

If we have a value of type int, we cannot directly pass it to a function expecting ServerState without converting it. This provides some degree of compile-time type safety for enums.

def main():
    ns = transition(ServerState.Idle)
    print(ns)

    ns2 = transition(ns)
    print(ns2)

def transition(s: ServerState) -> ServerState:
    if s == ServerState.Idle:
        return ServerState.Connected
    elif s in (ServerState.Connected, ServerState.Retrying):
        # Suppose we check some predicates here to determine the next state…
        return ServerState.Idle
    elif s == ServerState.Error:
        return ServerState.Error
    else:
        raise ValueError(f"unknown state: {s}")

if __name__ == "__main__":
    main()

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

To run the program, save the code to a file, for example enums.py, and execute it using Python.

$ python enums.py
connected
idle

Next example: Struct Embedding.


This example shows how to use enums in Python to achieve similar functionality as described in the original example.