如何在Ocaml中表示一个简单的有限状态机? [英] How to represent a simple finite state machine in Ocaml?
问题描述
我已经用C ++和Java编写了一些状态机,但从来没有像Ocaml这样的函数式语言。
问题是我不知道我是否可以修改代码对象语言版本,因为在Ocaml记录和变体比类更强大;
因此,我需要一个事件驱动的有限状态机(类似于UML的层次结构),可以很容易地配置
有人在该领域有经验的人可以发表一个简单的例子吗?只是为了避免最常见的陷阱
感谢:)
编辑 16 / 03:有没有可能做到没有可变状态?
我想正确地将它封装在名称FSM下,我应该选择一个模块还是一个类?
通常,您创建一个对应于自动机状态的记录,并且您有另一个类型的事件触发过渡到另一个状态。在状态记录中,您可以使用映射为每个事件查找新状态。
假设您的转换由字符串触发:
type event = string
module EventMap = Map.Make(struct
type t = event
let compare = compare
end)
type state = {
state_info:...; (*该状态的内容,id,注释等*)
mutable state_transitions:state EventMap.t;
}
让next_state current_state event =
尝试
EventMap.find事件current_state.state_transitions
with Not_found - > current_state
在这里,我假设未知的事件保持在相同的状态,但是你可能有一个错误状态在记录...
I have written some state machine in C++ and Java but never in a functional language like Ocaml
Problem is I don't know if I can just adapt code from the object languages versions, since in Ocaml records and variants are more powerful than class;
So, I need an event-driven finite state machine (hierarchical like in UML), easily configurable
Could someone experienced in the field post a simple sample of that ? Just to avoid the most common traps
thanks :)
EDIT 16/03 : Is it possible to do it without mutable state ? And I'd like to encapsulate it properly under the name "FSM", should I choose a module or a class ?
Usually, you create a record corresponding to a state of the automata, and you have another type for the event triggering the transition to another state. In the state record, you have a map to find, for each event, the new state.
Let's suppose your transitions are triggered by strings:
type event = string
module EventMap = Map.Make(struct
type t = event
let compare = compare
end)
type state = {
state_info : ...; (* the content of that state, id, comment, etc. *)
mutable state_transitions : state EventMap.t;
}
let next_state current_state event =
try
EventMap.find event current_state.state_transitions
with Not_found -> current_state
Here, I supposed that unknown events stay on the same state, but you could have an error state in the record...
这篇关于如何在Ocaml中表示一个简单的有限状态机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!