reactConsole

fun <S> reactConsole(initialState: S, stateToText: (S) -> String, nextState: (S, String) -> S, isTerminalState: (S) -> Boolean, terminalStateToText: (S) -> String = stateToText): S

An event-driven approach to decomposing console programs, which provides for explicit representation of state and functions to provide state-driven output, transition (via state and console input), and termination detection.

Example (REPL) usage:

>>> reactConsole(1, { "${it}!" }, { state,_ -> 2*state }, { it >= 100 }, { "fin." })
1!

2!
does not matter
4!
a
8!
b
16!
1
32!
2
64!

fin.
res1: kotlin.Int = 128

Notes:

  • This program will start at 1 (initial state) and after each (ignored via transition function) input

  • This program will stop once the state (the result of doubling) is greater than or equal to 100

  • While doubling, the output is just the current count (excitedly!), and once termination is achieved, simply "fin."

>>> reactConsole("", { "${it}!" }, { _,input -> input }, { it == "done" })
!
a
a!
b
b!
c
c!
done
done!
res1: kotlin.String = done

Notes:

  • The program excitedly (!) mirrors the most recent input (which captures state, initialized as an empty string).

  • The program ends when the input is "done", which is output one last time (since the final state->text function, since not supplied, is just the usual.

Return

state in which the program ended

Parameters

initialState

where the program begins

stateToText

function to produce the text representation of a state

nextState

function to transition to the next state based upon current state and supplied input

isTerminalState

predicate to determine if the program should end

terminalStateToText

(optional) function to produce the text representation of a terminal state