【问题标题】:Julia: unintended extension of base functionsJulia:基函数的意外扩展
【发布时间】:2018-11-23 03:27:35
【问题描述】:

我有以下不完整的 Julia 代码:

mutable struct Env
end

function step(env, action:UInt32)
    return ones(8), 1.0, true, Dict()
end

function reset(env)
    return ones(8)
end

当我尝试使用它时,我收到以下错误:

LoadError:方法定义错误:函数 Base.step 必须是 显式导入以进行扩展 LoadError:方法定义中的错误:函数 Base.reset 必须是 显式导入以进行扩展

我不知道 Base.step 和 Base.reset 是什么,我不想扩展它们。

我有什么方法可以保留这些函数名而不扩展基本函数吗?如果我只是用我完全不相关的方法扩展基本功能,会有问题吗?

我真的不想更改我的函数的名称,因为我想让它们与OpenAI Gym API 保持一致。

【问题讨论】:

    标签: julia


    【解决方案1】:

    在这样的模块中定义它们

    module Gym
    
    mutable struct Env
    end
    
    function step(env, action::UInt32)
        return ones(8), 1.0, true, Dict()
    end
    
    function reset(env)
        return ones(8)
    end
    
    end
    

    然后您可以在模块内直接调用它们为stepreset。在模块之外,您必须像这样限定它们:Gym.stepGym.reset

    另外 - 请注意,只有在 Main 模块中引入 stepreset 之后,然后再尝试扩展它们(例如,通过调用或引用它们),才会遇到此问题。因此,当开始一个干净的 Julia 会话时,这将起作用:

    $ julia
                   _
       _       _ _(_)_     |  Documentation: https://docs.julialang.org
      (_)     | (_) (_)    |
       _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
      | | | | | | |/ _` |  |
      | | |_| | | | (_| |  |  Version 1.0.2 (2018-11-08)
     _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
    |__/                   |
    
    julia> step(x) = x
    step (generic function with 1 method)
    

    但这会失败:

    $ julia
                   _
       _       _ _(_)_     |  Documentation: https://docs.julialang.org
      (_)     | (_) (_)    |
       _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
      | | | | | | |/ _` |  |
      | | |_| | | | (_| |  |  Version 1.0.2 (2018-11-08)
     _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
    |__/                   |
    
    julia> step
    step (generic function with 4 methods)
    
    julia> step(x) = x
    ERROR: error in method definition: function Base.step must be explicitly imported to be extended
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-18
      • 2012-02-22
      • 2017-08-27
      • 2021-12-08
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多