I'm trying to create a simple state machine in F# but having trouble getting two states with circular dependencies to work.
I have this state factory:
open System
let createState produceInput stateSwitchRule nextState =
let rec stateFunc() =
match produceInput() with
| x when x = stateSwitchRule -> printfn "%s" "Switching state"; nextState()
| _ -> printfn "%s" "Bad input. Try again"; stateFunc()
stateFunc
which I use to create two mutually recursive states:
let rec pongState() = createState Console.ReadLine "go to ping" pingState
and pingState = createState Console.ReadLine "go to pong" (pongState())
[<EntryPoint>]
let main argv =
pingState()
0
When invoking pingState()
and inputting "go to pong" the state is switched to pong. But when invoking inputting "go to ping" a null reference exception is thrown.
Is there anyway around this with the chosen approach or should I model it differently?