【发布时间】:2015-12-24 08:53:02
【问题描述】:
我正在尝试从Algorithms 4th Edition 实现以下代码
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# 中提出了以下实现:
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
()
我收到错误:预计有类型节点选项,但这里作为单位,在以下几行中:
| _ when t.Value < value -> t.Right <- Add t.Right value
| _ when t.Value > value -> t.Left <- Add t.Left value
有没有更好的方法来实现上面的代码?复制功能性方法中的程序样式代码是不是我犯了一个错误?
【问题讨论】:
-
使用有区别的联合可能比使用记录类型更简单;看一些粗略的sketch
标签: .net algorithm f# functional-programming binary-search-tree