2017-07-16 46 views
1

如何访问函数的主体?Julia:获取函数的主体

上下文:我有模块内的功能,我用特定的参数值执行。我想要“记录”这些参数值和相应的功能形式。下面我尝试:

module MainModule 

    using Parameters # Parameters provides unpack() macro 
    using DataFrames # DataFrames used to store results in a DataFrame 

    type ModelParameters 
     U::Function 
     γ::Float64 
    end 

    function ModelParameters(; 
     U::Function = c -> if γ == 1.0; log(c); else (c^(1-γ)-1)/(1-γ) end, 
     γ::Float64 = 2.0, 
     ) 
     ModelParameters(U, γ) 
    end 

    function show_constants(mp::ModelParameters) 
     @unpack γ = ModelParameters(mp) 
     d = DataFrame(
      Name = ["γ"], 
      Description = ["parameter of the function"], 
      Value = [γ] 
     ) 
     return(d) 
    end 

    function show_functions(mp::ModelParameters) 
     @unpack U = ModelParameters(mp) 
     d = DataFrame(
      Name = ["U"], 
      Description = ["function"], 
      Value = [U] 
     ) 
     return d 
    end 


    export 
    ModelParameters 
    show_constants, 
    show_functions 

    end # end of main module 

现在我执行模拟并作好记录:

using MainModule 
    mp = ModelParameters() 

    MainModule.show_constants(mp) 
    1×3 DataFrames.DataFrame 
    │ Row │ Name │ Description     │ Value │ 
    ├─────┼──────┼─────────────────────────────┼───────┤ 
    │ 1 │ "γ" │ "parameter of the function" │ 2.0 │ 

    MainModule.show_functions(mp) 
    1×3 DataFrames.DataFrame 
    │ Row │ Name │ Description │ Value   │ 
    ├─────┼──────┼─────────────┼───────────────┤ 
    │ 1 │ "U" │ "function" │ MainModule.#2 │ 

所以我的方法适用于参数值,但不具有的功能。我怎么可以用下面的东西代替MainModule.#2

选项(ⅰ)

c -> if γ == 1.0; log(c); else (c^(1-γ)-1)/(1-γ) end,

选择(ii)(代γ的数值= 2.0)

(c^(1-2.0)-1)/(1-2.0) 或简化版本如1-c^(-1.0)

我的问题与有关,但更容易,因为函数的主体不是“丢失”,但容易在我的来源。

+0

FYI,[Sugar.jl](https://github.com/SimonDanisch/Sugar.jl) – Gnimuc

+1

[检索方法的内容作为\的可能的复制' (https://stackoverflow.com/questions/42514371/retrieve-method-content-as-an-expression) –

回答

1

你可以找到一个类似的讨论here,为适应在我看来单行功能最好的解决办法是这样的:

type mytype 
    f::Function 
    s::String 
end 

mytype(x::String) = mytype(eval(parse(x)), x) 
Base.show(io::IO, x::mytype) = print(io, x.s) 

,而不是交出一个函数作为表达你给它作为一个字符串:

t = mytype("x -> x^2") 

你这样调用

t.f(3) 
功能

并访问字符串表示这样的:

t.s 
+0

我一定错过了你的答案,因为它是在八月的一个假期中!我接受它。请注意,这里有一个密切相关的问题,即重复:https://stackoverflow.com/questions/42514371/retrieve-method-content-as-an-expression – PatrickT