gpt4 book ai didi

julia - Julia 的链表

转载 作者:行者123 更新时间:2023-12-05 08:41:49 27 4
gpt4 key购买 nike

谁能帮我理解接下来的事情:
1)为什么我们需要在制作链表的同时制作一个 future 结构的新抽象类?
2) 为什么有参数 T?
3)这个操作符是干什么的<:(书上没找到)?
4) 我们可以用下面的方式来代替 Example 吗?:

type LinkedList 
name = Ptr{Uint8}
next :: LinkedList
end

例子:

abstract type LinkedList{T} end

mutable struct Nil{T} <: LinkedList{T}
end

mutable struct Cons{T} <: LinkedList{T}
head::T
tail::LinkedList{T}
end

谢谢!

最佳答案

  1. 你不知道。您实际上可以像您发布的那样定义递归结构。好吧,有点。 name = Ptr{Uint8}不是正确的语法——相反你想要 name::Ptr{UInt8} .虽然,实际上,您可能真的只想要 name::String .现在你仍然会遇到麻烦:

    julia> struct BrokenList
    name::String
    next::BrokenList
    end

    julia> BrokenList("first", BrokenList("last", #= uh, what goes here? =# ))

    您需要一些 BrokenList 类型的东西已经存在……但是为了创建一个你需要一个!所以一个简单的“out”就是允许 next要么是列表的另一个节点,要么是最后一个元素的某个占位符。 nothing (类型为 Nothing )是一个简单的选项:

    julia> struct BetterList
    name::String
    next::Union{BetterList, Nothing}
    end

    julia> BetterList("first", BetterList("last", nothing))
    BetterList("first", BetterList("last", nothing))
  2. 那个T不是争论;这是一个type parameter .当然,我们的BetterList可以轻松持有 Int s 而不是 String s…所以我们可以使用类型参数根据它所持有的值动态地参数化类型:

    julia> struct LinkedList{T}
    value::T
    next::Union{LinkedList{T}, Nothing}
    end

    julia> LinkedList("first", LinkedList("last", nothing))
    LinkedList{String}("first", LinkedList{String}("last", nothing))

    julia> LinkedList(1, LinkedList(2, nothing))
    LinkedList{Int64}(1, LinkedList{Int64}(2, nothing))
  3. 而不是使用 Union s,您发布的示例代码使用抽象类型和子类型来描述具有节点或最终 nil 元素的可能性。 <:subtyping operator .

关于julia - Julia 的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47273167/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com