簡體   English   中英

Python和F#中的遞歸變量定義(可能也是OCaml)

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

給定這些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”,我們不必按照拓撲排序定義的順序進行分配...(例如,狀態0是根據狀態1定義的,即使狀態1是稍后定義的)。

PS使用字符串作為狀態標識符的選項...

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 ...
## a generic state machine framework ###################

class Message(object):
    """
    This represents a message being passed to the
    state machine.
    """
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return "Message(%r)" % self.name
    def __call__(self, smap):
        try:
            return smap[self]
        except KeyError:
            raise Exception("invalid message: %s vs %s"
                            % (self, smap))

class MessageFactory(object):
    """
    Since python doesn't have symbols, this automagically
    creates the messages for you. (It's purely for
    convenience, and you could just as easily instantiate
    each message by hand.
    """
    cache = {}
    def __getattr__(self, name):
        return self.cache.setdefault(name, Message(name))

class StateMachine(object):
    """
    This keeps track of the state, of course. :)
    """
    def __init__(self, state):
        self.state = state
    def __call__(self, msg):
        self.state = self.state(msg)


## how to set it up: ###################################

msg = MessageFactory()
state =\
{
    0 : lambda m: m({ msg.A : state[1],
                      msg.B : state[2] }),
    1 : lambda m: m({ msg.B : state[3] }),
    2 : lambda m: m({ msg.A : state[3] }),
    3 : lambda m: m({ msg.C : state[4] }),
    4 : lambda m: m({ msg.D : state[5] }),
    5 : lambda m: m({ }),
}

## how to use it: ######################################

s = StateMachine(state[0])
s(msg.A)
assert s.state is state[1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM