开发者

transition function of a automaton

开发者 https://www.devze.com 2023-01-27 15:13 出处:网络
My goal is to implement a transition function in OCaml which takes in input an state and a character is returns a positive Boolean formula(including true and false).

My goal is to implement a transition function in OCaml which takes in input an state and a character is returns a positive Boolean formula(including true and false). That开发者_运维问答 is: \delta(q0,a) = q1 and (q2 or q3)

my problem is how to represent a boolean formula in ocaml and how implement the transition function with this specific


Alternating finite automaton, eh?

Representing a boolean formula would be done with a simple recursive variant type (that I'm going to make into a polymorphic type because I don't want to specify the type of a state yet):

type ’state formula = 
  | And      of ’state formula list
  | Or       of ’state formula list
  | Literal  of bool
  | Variable of ’state

So, for instance, q1 and (q2 or q3) would be represented as:

And [ Variable q1 ; Or [ Variable q2 ; Variable q3 ] ]

You may represent the function as either an actual OCaml function:

type state = Q0 | Q1 | Q2 | Q3
let delta : state * char -> state formula = function 
  | Q0, 'a' -> And [ Variable Q1 ; Or [ Variable Q2 ; Variable Q3 ] ]
  | _ -> ...

Or you may opt for storing the transitions in a map (this lets you build your automaton at runtime):

type state = int

module OrderedStateChar = struct
  type = state * char
  let compare = compare
end

module StateCharMap = Map.Make(OrderedStateChar)  

let transition_of_map map = 
  fun (state,char) -> 
    try StateCharMap.find (state,char) map 
    with Not_found -> Literal false

let map = List.fold_left 
  (fun map (state,char,formula) -> StateCharMap.add (state,char) formula map)
  StateCharMap.empty 
  [ 
    0, 'a', And [ Variable 1 ; Or [ Variable 2 ; Variable 3 ] ] ;
    ...
  ]

let transition = transition_of_map map

let _ = transition (0,'a') (*/* returns '1 and (2 or 3)' */*)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号