【问题标题】:How to implement add operation in Binary Search Tree in F#?如何在 F# 中实现二叉搜索树的加法操作?
【发布时间】: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


【解决方案1】:

您收到错误是因为 None 匹配返回 Some Node,因此您必须在所有其他分支中匹配该返回类型。

您可以通过在匹配后返回节点来解决其他匹配中的问题:

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
            Some t
        | _ when t.Value > value ->
            t.Left <- Add t.Left value
            Some t
        | _ ->
            t.Value <- value
            //t.Count <- (x.Size t.Left) + (x.Size t.Right) + 1
            Some t

(你可能注意到我注释掉了倒数第二行,因为x 没有Size 成员。)

我是否在复制函数式方法中的程序样式代码时犯了错误?

大概吧。这取决于你的目标是什么。如果您想学习 F# 的 语法,这可能是一个很好的练习。如果你想学习函数式编程,那么这样做是没有意义的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    相关资源
    最近更新 更多