自动机的过渡功能

时间:2010-11-26 11:24:54

标签: functional-programming ocaml automaton

我的目标是在OCaml中实现一个转换函数,它接受一个输入状态,一个字符返回一个正布尔公式(包括true和false)。 即:\ delta(q0,a)= q1和(q2或q3)

我的问题是如何在ocaml中表示布尔公式以及如何使用此特定实现转换函数

1 个答案:

答案 0 :(得分:2)

交替有限自动机,嗯?

用一个简单的递归变量类型表示一个布尔公式(我将把它变成一个多态类型,因为我还不想指定一个状态的类型):

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

因此,例如,q1 and (q2 or q3)将表示为:

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

您可以将该函数表示为实际的OCaml函数:

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

或者您可以选择将转换存储在地图中(这样可以在运行时构建自动机):

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)' */*)