我正在尝试实现来自《算法 第四版》的以下代码:
我已经想出了以下的F#实现:
private Node put(Node x, Key key, Value val)
{
if (x == null) return new Node(key, val, 1);
int cmp = key.compareTo(x.key);
if (cmp < 0) x.left = put(x.left, key, val);
else if (cmp > 0) x.right = put(x.right, key, val);
else x.val = val;
x.N = size(x.left) + size(x.right) + 1;
return x;
}
我已经想出了以下的F#实现:
我已经想出了以下的F#实现:
type Node = {
mutable Left : Node option
mutable Right : Node option
mutable Value : int
mutable Count : int
}
type BST() =
let root : Node option = None
member x.Put (value : int) =
let rec Add (node:Node option) value =
match node with
| None -> Some { Left = None; Right = None; Value = value; Count = 1 }
| Some t ->
match t with
| _ when t.Value < value -> t.Right <- Add t.Right value
| _ when t.Value > value -> t.Left <- Add t.Left value
| _ ->
t.Value <- value
t.Count <- (x.Size t.Left) + (x.Size t.Right) + 1
Some t
()
我遇到了错误:在以下行中,预期类型为Node option,但此处为unit:
| _ when t.Value < value -> t.Right <- Add t.Right value
| _ when t.Value > value -> t.Left <- Add t.Left value
有没有更好的方法来实现上面的代码?如果直接将过程式风格的代码复制到函数式代码中,会犯错吗?