如果你想使用纯粹的功能表示,nlucaroni建议的拉链确实是在数据结构深处表示光标的好方法,可以移动或用于更新结构.
如果您希望使用就地变异的解决方案,可以通过mutable记录字段或ref从其派生的references()使用可变数据.例如:
type 'a tree_cell = {mutable node : 'a tree}
and 'a tree = Leaf of 'a | Branch of 'a tree_cell * 'a * 'a tree_cell
Run Code Online (Sandbox Code Playgroud)
如果你持有'a tree_cell,你可以改变它(在恒定的时间).
let head {node = (Leaf x | Branch(_, x, _))} = x
let duplicate cell =
cell.node <- Branch (cell, head cell, {node = cell.node})
Run Code Online (Sandbox Code Playgroud)
编辑:在您的问题的评论中,您似乎表明您对n-ary树的解决方案感兴趣.
一般的n-ary案例可以表示为
type 'a tree_cell = {mutable node: 'a tree}
and 'a tree = Branch of 'a * 'a tree_cell list
Run Code Online (Sandbox Code Playgroud)
而拉链解决方案看起来像(未经测试的代码)
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
Run Code Online (Sandbox Code Playgroud)