编程语言
首页 > 编程语言> > Python和F#中的递归变量定义(也可能是OCaml)

Python和F#中的递归变量定义(也可能是OCaml)

作者:互联网

鉴于这些F#类型声明……

type Message =
    | MessageA
    | MessageB
    | MessageC
    | MessageD

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

…对这个特定的状态机有一个同样富有表现力的定义……

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}

…用Python?

请注意,通过“rec”,我们不必按拓扑排序定义的顺序进行分配…(例如,state0是根据state1定义的,即使稍后定义了state1).

附:使用字符串作为状态标识符的选项……

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

…打开无效密钥的情况(即状态机中的无效消息说明符).

解决方法:

在Python中,我认为您将定义状态,然后设置地图.伪代码如:

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 ...

标签:python,f,ocaml,recursive-datastructures
来源: https://codeday.me/bug/20190521/1149059.html