How to represent a simple finite state machine in Ocaml?

后端 未结 4 1339
青春惊慌失措
青春惊慌失措 2021-02-04 08:24

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 languag

4条回答
  •  孤独总比滥情好
    2021-02-04 08:55

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

提交回复
热议问题