Julia 朱莉娅:获取函数体

Julia 朱莉娅:获取函数体,julia,Julia,如何访问函数体? 上下文:我在模块内有函数,我使用特定的参数值执行这些函数。我想“记录”这些参数值和相应的函数形式。下面是我的尝试: module MyModule using Parameters # Parameters provides unpack() macro using DataFrames # DataFrames used to store results in a DataFrame struct ModelParameters γ::Float64

如何访问函数体?

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

module MyModule

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

struct ModelParameters
    γ::Float64
    U::Function
end

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

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

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


export
ModelParameters
show_constants,
show_functions

end  # end of MyModule
记录:

using Main.MyModule
mp = ModelParameters()

MyModule.show_constants(mp)

1×3 DataFrame
 Row │ Name    Description     Value   
     │ String  String          Float64 
─────┼─────────────────────────────────
   1 │ γ       parameter of U      2.0


MyModule.show_functions(mp)

1×3 DataFrame
 Row │ Name    Description                Value 
     │ String  String                     #2#4… 
─────┼──────────────────────────────────────────
   1 │ U       function with parameter γ  #2
这对于存储标量和数组值非常有用,但对于函数则不是。我怎样才能用有用的东西来代替
#2

有用的示例:

c->如果γ==1.0;对数(c);else(c^(1-γ)-1)/(1-γ)end,

(c^(1-2.0)-1)/(1-2.0)

或者(神奇地简化):

1-c^(-1.0)


我的问题与此有点相关。

您可以找到类似的讨论,在我看来,适合单行函数的最佳解决方案如下:

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.s
不是将函数作为表达式进行传递,而是将其作为字符串进行传递:

t = mytype("x -> x^2")
你这样调用函数

t.f(3) 
并按如下方式访问字符串表示:

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.s

仅供参考,可能的副本请更新您的答案,使其与Julia 1.0+兼容。谢谢