【问题标题】:Problem when using type Any for mutiple-dispatch in Julia在 Julia 中使用类型 Any 进行多次分派时出现问题
【发布时间】:2022-11-17 05:36:05
【问题描述】:

我正在尝试编写一个接收元组和字典作为参数的函数。

function findBestAction(state::Tuple{Int64, Int64}, qTable::Dict{Any, Matrix{Float64}})
   doSomething()
end

我希望函数接收其键可以是任何可能类型的字典。我运行以下命令但收到错误消息:

findBestAction((0, 0), qTable) #qTable::Dict{String, Matrix{Float64}}

错误信息:

Stacktrace:
 [1] top-level scope
   @ e:\Master Thesis\lu_jizhou\Learning\q_learning.jl:33

ERROR: MethodError: no method matching findBestAction(::Tuple{Int64, Int64}, ::Dict{String, Matrix{Float64}})
Closest candidates are:
  findBestAction(::Tuple{Int64, Int64}, ::Dict{Any, Matrix{Float64}}) at e:\Master Thesis\lu_jizhou\Learning\q_learning.jl:33
Stacktrace:
 [1] top-level scope
   @ e:\Master Thesis\lu_jizhou\Learning\q_learning.jl:48

我该怎么做?

【问题讨论】:

    标签: julia any


    【解决方案1】:

    这是因为Dict{String, ...)不是Dict{Any, ...) 的子类型。

    这就是参数类型(即在花括号中包含其他类型的类型)在 Julia 中的行为方式。来自 Julia 手册section on Parametric types

    julia> Point{Float64} <: Point{Real} 
    false
    

    警告

    最后一点非常重要:尽管Float64 &lt;: Real我们确实这样做了 没有Point{Float64} &lt;: Point{Real}

    换句话说,按照类型理论的说法,Julia 的类型 参数不变

    您可以改为将函数编写为

    function findBestAction(state::Tuple{Int64, Int64}, qTable::Dict{<:Any, Matrix{Float64}})
       doSomething()
    end
    

    其中明确指出 Any 的任何子类型都可以作为 Dict 中的键类型。

    您还可以考虑将 Dict 更改为 AbstractDict,并将其值类型更改为类似于 &lt;:AbstractMatrix{&lt;:Real},如果您的代码是以适用于任何 AbstractMatrix 和任何 Real 的方式编写的亚型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-13
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      相关资源
      最近更新 更多