如何在Julia中定义二叉搜索树的类型?

如何在Julia中定义二叉搜索树的类型?,julia,union,Julia,Union,我尝试用以下方法定义Julia中整数的二元搜索树的类型: mutable struct BST key::Int left::Union{BST, Nothing} right::Union{BST, Nothing} end 现在我想定义构造函数和基本推!方法使用这种简单的方法: BST(key::Int) = BST(key, Nothing, Nothing) BST() = BST(0) function Base.push!(node::BST, key)

我尝试用以下方法定义Julia中整数的二元搜索树的类型:

mutable  struct BST
    key::Int
    left::Union{BST, Nothing}
    right::Union{BST, Nothing}
end
现在我想定义构造函数和基本推!方法使用这种简单的方法:

BST(key::Int) = BST(key, Nothing, Nothing)
BST() = BST(0)

function Base.push!(node::BST, key)
    if key < node.key
        if node.left.isnull
            node.left = BST(key)
        else
            push!(node.left.value, key)
        end
    elseif key > node.key
        if node.right.isnull
            node.right = BST(key)
        else
            push!(node.right.value, key)
        end
    end
end

root = BST()
push!(root, 1)
push!(root, 2)
当然,它不适用于Julia 1.0!我当然不太明白union的用法。它们只是抽象类型吗?定义此数据结构的正确方法是什么

朱莉娅不善于解释这个话题

前面的一个问题使用现在不推荐使用的Nullable类型解决了该主题:

下面是代码的外观,它假设您不想在BST中存储重复的值,但我想这就是您想要的:

BST(key::Int) = BST(key, nothing, nothing)
BST() = BST(0)

function Base.push!(node::BST, key)
    if key < node.key
        if node.left === nothing
            node.left = BST(key)
        else
            push!(node.left, key)
        end
    elseif key > node.key
        if node.right === nothing
            node.right = BST(key)
        else
            push!(node.right, key)
        end
    end
end
事实上,您的定义几乎没有问题,只是有一些小的语法问题:

nothing是一个值,nothing是一个类型,所以您必须编写BSTkey,nothing,nothing不是BSTkey,nothing,nothing 您可以使用这种比较节点来测试某个东西是否为空。left==nothing use==这样编译器就可以更轻松地优化此代码 你得推!到BST对象,而不是存储在其中的值,所以推!node.right,不要按键!node.right.value,键
下面是代码的外观,它假设您不想在BST中存储重复的值,但我猜这就是您想要的:

BST(key::Int) = BST(key, nothing, nothing)
BST() = BST(0)

function Base.push!(node::BST, key)
    if key < node.key
        if node.left === nothing
            node.left = BST(key)
        else
            push!(node.left, key)
        end
    elseif key > node.key
        if node.right === nothing
            node.right = BST(key)
        else
            push!(node.right, key)
        end
    end
end
事实上,您的定义几乎没有问题,只是有一些小的语法问题:

nothing是一个值,nothing是一个类型,所以您必须编写BSTkey,nothing,nothing不是BSTkey,nothing,nothing 您可以使用这种比较节点来测试某个东西是否为空。left==nothing use==这样编译器就可以更轻松地优化此代码 你得推!到BST对象,而不是存储在其中的值,所以推!node.right,不要按键!node.right.value,键
朱莉娅很优雅。谢谢。更重要的是,所有这些bug都被Julia编译器捕获了。当您有足够的阅读错误消息的经验时,就很容易修复它们。例如,第三个bug传递node.right.value以推送!将被一种不允许指定函数参数类型的语言默默地接受,并在一个意外的时刻回退。Julia很优雅。谢谢。更重要的是,所有这些bug都被Julia编译器捕获了。当您有足够的阅读错误消息的经验时,就很容易修复它们。例如,第三个bug传递node.right.value以推送!将被一种不允许指定函数参数类型的语言默默地接受,并在意外时刻回退。