Enums in PureScript

Our enumerated type ServerState has an underlying Int type.

module Main where

import Prelude
import Effect (Effect)
import Effect.Console (log)

-- Define an enumerated type
data ServerState = StateIdle | StateConnected | StateError | StateRetrying

-- Map each state to its string representation
stateName :: ServerState -> String
stateName StateIdle = "idle"
stateName StateConnected = "connected"
stateName StateError = "error"
stateName StateRetrying = "retrying"

-- Implement the Show type class for ServerState to convert it to a string
instance showServerState :: Show ServerState where
  show = stateName

-- State transition function
transition :: ServerState -> ServerState
transition StateIdle = StateConnected
transition StateConnected = StateIdle
transition StateRetrying = StateIdle
transition StateError = StateError

main :: Effect Unit
main = do
  let ns = transition StateIdle
  log (show ns)
  let ns2 = transition ns
  log (show ns2)

The possible values for ServerState are defined as a data type with different data constructors.

Implementing the Show type class allows values of ServerState to be converted to strings and printed out. If we have a function transition, it can switch between different states.

Running the program results in the following output:

$ spago run
connected
idle