任何人都可以帮助我理解接下来的事情:
1)为什么我们需要在创建链表的同时创建一个未来结构的新抽象类?
2) 为什么有一个参数 T?
3)这个操作符是做什么的<:(书上没找到)?
4) 我们可以用下面的方式来代替 Example 吗?:
type LinkedList
name = Ptr{Uint8}
next :: LinkedList
end
Run Code Online (Sandbox Code Playgroud)
例子:
abstract type LinkedList{T} end
mutable struct Nil{T} <: LinkedList{T}
end
mutable struct Cons{T} <: LinkedList{T}
head::T
tail::LinkedList{T}
end
Run Code Online (Sandbox Code Playgroud)
谢谢!
你没有。您实际上可以像您发布的那样定义递归结构。嗯,有点。 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? =# ))
Run Code Online (Sandbox Code Playgroud)
您需要某种类型的东西BrokenList已经存在……但是为了创建一个类型,您需要一个!所以一个简单的“out”是允许next成为列表的另一个节点或最后一个元素的某个占位符。nothing(这是 type Void)是一个简单的选项:
julia> struct BetterList
name::String
next::Union{BetterList, Void}
end
julia> BetterList("first", BetterList("last", nothing))
BetterList("first", BetterList("last", nothing))
Run Code Online (Sandbox Code Playgroud)那T不是争论;它是一个类型参数。当然,我们BetterList可以很容易地持有Ints 而不是Strings...所以我们可以使用类型参数根据它持有的值动态地参数化类型:
julia> struct LinkedList{T}
value::T
next::Union{LinkedList{T}, Void}
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))
Run Code Online (Sandbox Code Playgroud)Union您发布的示例代码没有使用s,而是使用抽象类型和子类型来描述具有节点或最终 nil 元素的可能性。 <:是子类型操作符。