在ocaml中定义树+指向其子树的指针

时间:2012-02-14 20:10:10

标签: list pointers tree constants ocaml

如何在OCaml中定义树+指向其子树的指针,以便在此子树中添加叶子需要恒定的时间?

2 个答案:

答案 0 :(得分:7)

如果你想使用纯粹的功能表示,nlucaroni建议的拉链确实是在数据结构深处表示光标的好方法,可以移动或用于更新结构。

如果您希望使用就地变异的解决方案,您可以通过mutable记录字段或从中派生的引用(ref)使用可变数据。例如:

type 'a tree_cell = {mutable node : 'a tree}
and 'a tree = Leaf of 'a | Branch of 'a tree_cell * 'a * 'a tree_cell

如果你持有'a tree_cell,你可以改变它(在恒定时间内)。

let head {node = (Leaf x | Branch(_, x, _))} = x

let duplicate cell =
  cell.node <- Branch (cell, head cell, {node = cell.node})

编辑在您的问题的评论中,您似乎表明您对n-ary树的解决方案感兴趣。

一般的n-ary案例可以表示为

type 'a tree_cell = {mutable node: 'a tree}
and 'a tree = Branch of 'a * 'a tree_cell list

虽然拉链解决方案看起来像(未经测试的代码)

type 'a tree = Branch of 'a * 'a forest
and 'a forest = 'a tree list

(* the data between the current cursor and the root of the tree *)
type 'a top_context = Top | Under of 'a * 'a tree * 'a top_context

(* a cursor on the 'data' element of a tree *)
type 'a data_cursor = top_context * 'a tree list

(* plug some data in the hole and get a tree back *)
val fill_data : 'a data_cursor -> 'a -> 'a tree

(* a cursor on one of the children of a tree *)
type 'a list_zipper = 'a list * 'a list
type 'a children_cursor = top_context * 'a * 'a tree list_zipper

(* plug some subtree in the hole and get a tree back *)
val fill_children : 'a children_cursor -> 'a tree -> 'a tree

(* carve a data hole at the root; also return what was in the hole *)
val top_data : 'a tree -> 'a data_cursor * 'a

(* fill a data hole and get a cursor for the first children in return
   -- if it exists *)
val move_down : 'a data_cursor -> 'a -> ('a children_cursor * 'a tree) option
(* fill the children hole and carve out the one on the left *)
val move_left : 'a data_cursor -> 'a tree -> ('a data_cursor * 'a tree) option
val move_right : 'a data_cursor -> 'a tree -> ('a data_cursor * 'a tree) option
(* fill the children hole and get a cursor on the data *)
val move_up : 'a children_cursor -> 'a tree -> 'a data_cursor * 'a

答案 1 :(得分:4)

二叉树的另一种(更简单,更通用)解决方案:

type 'a t = {
  value : 'a;
  mutable left : 'a t option;
  mutable right : 'a t option;
}

使用此类型,您可以根据需要独立设置左侧和右侧子树。