【发布时间】:2023-04-01 21:11:01
【问题描述】:
我正在 OCaml 中实现二叉搜索树,尝试使用尽可能多的命令式编程。
我有以下数据类型:
type tKey = Key of int;;
type tBST = Null | Pos of node ref
and node = {mutable key : tKey; mutable left : tBST; mutable right : tBST};;
我在使用此功能时遇到问题:
let createNode k tree =
tree := Pos ({key = k; left = Null; right = Null});;
Error: This record expression is expected to have type node ref
The field key does not belong to type ref
二叉搜索树可以是 Null(表示空树)或 Pos。树 Pos 是指向节点的指针,节点是键和其他 2 棵树(左和右)的结构。
我的主要目标是在函数结束后修改一棵树。通过引用传递树,所以当 createNode 结束时,我作为参数传递的 tBST 被修改。
问题:实际上可以在 OCaml 中做我正在尝试的事情吗?如果是这样,我怎么能改变我的函数 createNode 和/或数据类型来实现这一点?
非常感谢。
【问题讨论】:
标签: pointers ocaml binary-search-tree record imperative-programming