如何访问函数体?
上下文: 我在模块中有一些函数,我使用特定的参数值执行这些函数。我想“记录”这些参数值和对应的函数形式。在我的尝试之下:
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-γ) 结束,
或
(c^(1-2.0)-1)/(1-2.0)
或(神奇地简化):
1-c^(-1.0)
我的问题与 Julia: show body of function (to find lost code) 有点相关.
最佳答案
可以找到类似的讨论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
关于Julia:获取函数体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45134198/