3

我正在尝试实现一个正则表达式到 NFA 转换器。我已经编写了大部分代码,但是我正在努力寻找一种方法来构建具有循环的图形,因为我对状态(节点)和边的表示。

我的图形表示如下:

type state =
| State of int * edge list (* Node ID and outgoing edges *)
| Match (* Match state for the NFA: no outgoing edges *)
and edge =
| Edge of state * string (* End state and label *)
| Epsilon of state (* End state *)

我将正则表达式转换为 NFA 的函数基本上是对正则表达式类型的模式匹配,接受正则表达式类型和“最终状态”(NFA 的所有传出边都将去的地方)并返回“开始状态”该正则表达式的(部分构建的)NFA。NFA 片段是通过返回一个使用其传出边列表构造的状态来构建的,其中每个边的结束状态是通过递归调用构造的。

大多数代码都很简单,但是我在为 Kleene 星和 + 构建 NFA 时遇到了麻烦,这需要图中的循环。鉴于我的代表,我最终得到了类似的结果:

let rec regex2nfa regex final_state =
  match regex with
  ... (* Other cases... *)
  | KleeneStar(re) ->
      let s = State(count, [Epsilon(regex2nfa r s); Epsilon(final_state)]) in
      s

显然这不会编译,因为此时 s 是未定义的。但是我也不能添加“rec”关键字,因为类型检查器将(正确地)拒绝这种递归定义的类型,并且我无法通过使用 Lazy 来解决这个问题,因为强制评估“s”将递归地强制它(再次然后再次...)。基本上我在这里有一个先有鸡还是先有蛋的问题-我需要在“状态”引用完全构造之前将其传递到另一个状态,该状态将返回它,但是当然原始状态必须完全构造才能传递在递归调用中。

有没有办法在不使用引用/可变记录的情况下做到这一点?我真的很想尽可能保持它的功能,但鉴于这种情况,我看不到解决办法......有人有建议吗?

4

1 回答 1

1

您可以使用惰性类型或函数创建具有循环而无需显式引用的数据结构。事实上,它们都隐藏了某种形式的可变性。

这是一个最简单的惰性结构的示例,它比列表更复杂

type 'a tree = 'a tr Lazy.t
and  'a tr = Stem of 'a * 'a tree * 'a tree

let rec tree_with_loop : int tree =
  lazy (Stem (42,tree_with_loop,tree_with_loop))

但是,您应该明白,使用这种结构(即包含循环的结构),您正踏入无限的软弱基础,因为您的所有遍历功能现在都发散了。

这是相同的示例,但没有惰性:

type 'a tree = unit -> 'a tr
and  'a tr = Stem of 'a * 'a tree * 'a tree

let rec tree_with_loop : int tree =
  fun () -> Stem (42,tree_with_loop,tree_with_loop)

这是一个稍微少一点的无限树的例子:

type 'a tree = 'a tr Lazy.t
and  'a tr =
  | Node of 'a
  | Tree of 'a tree * 'a tree

let rec tree_with_loop : int tree =
  lazy (Tree (tree_with_loop,
              lazy (Node 42)))
于 2014-05-07T06:27:44.693 回答