Julia: Get body of a function
如何访问函数主体?
上下文:我在模块内部具有函数,这些函数通过特定的参数值执行。 我想"保留记录"这些参数值和相应的功能形式。 在我的尝试之下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 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 |
现在,我执行模拟并保留记录:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 │ |
因此,我的方法适用于参数值,而不适用于函数。 如何用以下内容替换
选项(i)
选项(ii)(用γ的数值代替2.0)
或简化版本,例如
我的问题与Julia有关:显示函数主体(查找丢失的代码),但是更容易,因为函数主体不是"丢失"的,而是在我的资料中容易获得的。
您可以在此处找到类似的讨论,我认为适合单行功能的最佳解决方案是这样的:
1 2 3 4 5 6 7 | 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) |
而不是将函数作为表达式移交给您,而是将其作为String给出:
1 | t = mytype("x -> x^2") |
你这样调用函数
1 | t.f(3) |
并像这样访问String表示形式:
1 | t.s |