Enums in Standard ML

Here’s how you can translate the Go code example to Standard ML with an explanation 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. Standard ML 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.

datatype ServerState = 
    StateIdle 
  | StateConnected 
  | StateError 
  | StateRetrying

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

fun stateToString StateIdle = "idle"
  | stateToString StateConnected = "connected"
  | stateToString StateError = "error"
  | stateToString StateRetrying = "retrying"

If we have a value of type int, we cannot pass it to transition - the compiler will complain about type mismatch. This provides some degree of compile-time type safety for enums.

fun main() =
  let
    val ns = transition StateIdle
  in
    print (stateToString ns ^ "\n");
    val ns2 = transition ns
  in
    print (stateToString ns2 ^ "\n")
  end

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

fun transition StateIdle = StateConnected
  | transition StateConnected = StateIdle
  | transition StateRetrying = StateIdle
  | transition StateError = StateError
  | transition _ = raise Fail "unknown state"

To run the program, save the code in a file called server-state.sml and use an SML interpreter such as smlnj to execute it.

$ sml server-state.sml
connected
idle

Next example: Struct Embedding.


This translation maintains the structure and explanation provided in the original example, adapting it to the syntax and idioms of Standard ML.