Class 在OCaml中具有类的红黑树
有人知道如何用OCaml中的类实现红黑树吗? 至少是类属性和初始值设定项?我是OCaml的新手 我尝试的是:Class 在OCaml中具有类的红黑树,class,oop,ocaml,binary-tree,red-black-tree,Class,Oop,Ocaml,Binary Tree,Red Black Tree,有人知道如何用OCaml中的类实现红黑树吗? 至少是类属性和初始值设定项?我是OCaml的新手 我尝试的是: type data = {key: int; value: string} class node (data: data) = object (self) val mutable d = data val mutable color = 1 val mutable left = ref (None: node option) val mutable
type data = {key: int; value: string}
class node (data: data) =
object (self)
val mutable d = data
val mutable color = 1
val mutable left = ref (None: node option)
val mutable right = ref (None: node option)
val mutable parent = ref (None: node option)
method getLeft = left
method getRight = right
method getParent = parent
method getColor = color
method getData = d
method setLeft (l: node option ref) = left := !l
method setRight (l: node option ref) = right := !l
method setParent (l: node option ref) = parent := !l
end;;
class rbtree =
object (self)
val mutable root = ref (None: node option)
val mutable nullNode = ref (None: node option)
method searchNode (aNode: node option ref) (key: data) = begin
if aNode = nullNode || key == (!aNode)#getData then aNode;
end;
end;;
我得到错误这个表达式有类型节点选项
它没有getData方法
我想做的是用C++编写这样的代码:
struct Node
{
int data;
Node *parent;
Node *left;
Node *right;
int color;
};
typedef Node *NodePtr;
class RedBlackTree
{
private:
NodePtr root;
NodePtr TNULL;
void initializeNULLNode(NodePtr node, NodePtr parent)
{
node->data = 0;
node->parent = parent;
node->left = nullptr;
node->right = nullptr;
node->color = 0;
}
NodePtr searchTreeHelper(NodePtr node, int key)
{
if (node == TNULL || key == node->data)
{
return node;
}
if (key < node->data)
{
return searchTreeHelper(node->left, key);
}
return searchTreeHelper(node->right, key);
}
};
struct节点
{
int数据;
节点*父节点;
节点*左;
节点*右;
内色;
};
typedef节点*NodePtr;
类红黑树
{
私人:
无柄根;
NodePtr-TNULL;
void initializeNULLNode(NodePtr节点,NodePtr父节点)
{
节点->数据=0;
节点->父节点=父节点;
节点->左=空PTR;
节点->右=nullptr;
节点->颜色=0;
}
NodePtr searchTreeHelper(NodePtr节点,int键)
{
if(node==TNULL | | key==node->data)
{
返回节点;
}
if(键<节点->数据)
{
返回searchTreeHelper(节点->左,键);
}
返回searchTreeHelper(节点->右侧,键);
}
};
对于您看到的错误,@Shon是正确的。你有这样的表达:
if aNode = nullNode || key == (!aNode)#getData then aNode;
阳极的类型为节点选项ref
。这意味着的类型!阳极
是节点选项
。选项值不是对象(类的实例)。因此,您不能对其调用方法getData
同样,正如@Shon所说,您需要检索的值!阳极
(如果有)。这将为您提供一个节点,它是一个对象,具有getData
方法
在您的if
测试中在线编写此代码会很麻烦。因此,您可以编写如下函数:
let node_option_has_value node_opt value =
match node_opt with
| None -> false
| Some node -> node#getData = value
作为旁注,您不应该使用物理相等运算符(==
)进行比较。此操作器用于特殊情况,而不是一般用途
OCaml中的相等比较运算符是
=
(如我的示例代码所示)。很难回答这个问题,因为没有明确的理由使用类来表示树类型。此外,你说“类”,好像你期望有不止一个类。如果您更仔细地解释您的需求,可能会有所帮助。然而,这听起来像是家庭作业,你应该准备好自己做几乎所有的工作。特别是,您最好在编写一些代码并遇到具体问题后再提出问题。谢谢您的回答。是的,你说得对。这是家庭作业。我现在将用我尝试过的代码更新我的问题。@JeffreyScofield,你现在能再看一遍吗?谢谢。关于错误,此表达式具有类型节点选项。它没有方法getData
看起来这是因为该值的类型为节点选项
,但您正在尝试访问类型为节点
的值的字段。因此,您需要首先从选项
中获取节点
。请看-总结是,这不是一个理想的方式来解决志愿者,可能会适得其反获得答案。请不要将此添加到您的问题中。