如何访问函数的主体?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)
我的问题与有关,但更容易,因为函数的主体不是“丢失”,但容易在我的来源。
FYI,[Sugar.jl](https://github.com/SimonDanisch/Sugar.jl) – Gnimuc
[检索方法的内容作为\的可能的复制' (https://stackoverflow.com/questions/42514371/retrieve-method-content-as-an-expression) –