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

2024-10-03 04:29:57 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑到这些F#type声明。。。在

type Message =
    | MessageA
    | MessageB
    | MessageC
    | MessageD

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

……对于这个特定的状态机,有没有一个同样具有表达力的定义。。。在

^{pr2}$

…用Python?在

注意,通过“rec”,我们不必按照拓扑排序定义的顺序进行赋值。。。(例如,state0是根据state1定义的,即使state1是在后面定义的)。在

另外,使用字符串作为状态标识符的选项。。。在

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

…保留无效键(即状态机中的无效消息说明符)的情况。在


Tags: name声明mapmessagestring定义typestate
2条回答

在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]

相关问题 更多 >