関数の本体にアクセスするにはどうすればよいですか?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
を次のようなものに置き換えるにはどうすればよいですか?
オプション(I)
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)
私の質問はに関連しています関数の本体が "失われていない"ので、私のソースでは簡単に利用できるので、でも簡単です。あなたはそれを与える式として
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)
代わりの機能受け渡し:
、[Sugar.jl](https://github.com/SimonDanisch/Sugar.jl) – Gnimuc
可能重複Expr \ 'session](https://stackoverflow.com/questions/42514371/retrieve-method-content-as-an-expression) –