Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive variable definitions in Python and F# (probably OCaml, too)

Given these F# type declarations...

type Message =
    | MessageA
    | MessageB
    | MessageC
    | MessageD

type State = {
    Name:string
    NextStateMap: Map<Message,State>
}

...is there an equally expressive definition of this specific state machine...

let rec state0 = { Name = "0"; NextStateMap = Map.ofList [ (MessageA,state1); (MessageB,state2)] }
    and state1 = { Name = "1"; NextStateMap = Map.ofList [ (MessageB,state3)] }
    and state2 = { Name = "2"; NextStateMap = Map.ofList [ (MessageA,state3)] }
    and state3 = { Name = "3"; NextStateMap = Map.ofList [ (MessageC,state4)] }
    and state4 = { Name = "4"; NextStateMap = Map.ofList [ (MessageD,state5)] }
    and state5 = { Name = "5"; NextStateMap = Map.empty}

...with Python?

Note that via the "rec", we didn't have to do assignments in an order defined by a topological sort... (e.g. state0 is defined in terms of state1, even though state1 is defined later on).

P.S. The option of using strings as state identifiers...

stateMachine = {
   "0" : { "A":"1", "B":"2"},
   "1" : { "B":"3" },
...

...leaves open the case of invalid keys (i.e. invalid message specifiers in the state machine).

like image 633
ttsiodras Avatar asked Feb 25 '11 15:02

ttsiodras


1 Answers

In Python I think you'd define the states and then set the map. Pseudo-code like:

state0 = State("0")
state1 = State("1")
... and so on ...
state0.next_states = {message_a: state1, message_b: state2 }
state1.next_states = {message_b: state3}
... and so on ...
like image 77
Duncan Avatar answered Sep 25 '22 04:09

Duncan