Julia:获取函数体

3

如何访问函数的主体?

背景:我在模块内有一些函数,我会使用特定的参数值来执行这些函数。我想要“记录”这些参数值和相应的函数形式。以下是我的尝试:

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
 RowName    Description     ValueString  String          Float64 
─────┼─────────────────────────────────
   1 │ γ       parameter of U      2.0


MyModule.show_functions(mp)

1×3 DataFrame
 RowName    Description                ValueString  String                     #2#4… 
─────┼──────────────────────────────────────────
   1U       function with parameter γ  #2

这对于存储标量和数组值非常有用,但不适用于函数。我该如何用实用的东西替换#2

以下是有用的示例:

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

或者

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

或者(神奇地简化):

1-c^(-1.0)

我的问题与Julia:显示函数主体(以查找丢失的代码)有些相关。


FYI,Sugar.jl - Gnimuc
1
可能是检索方法内容作为`Expr`ession的重复问题。 - mbauman
1个回答

1
你可以在这里找到类似的讨论。在我看来,适合单行函数的最佳解决方案是这样的:
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

请问您能否更新您的答案,使其适用于Julia 1.0+吗?谢谢! - PatrickT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接