Wie kann ich auf den Körper einer Funktion zugreifen?Julia: Get Körper einer Funktion
Kontext: Ich habe Funktionen in Modulen, die ich mit bestimmten Parameterwerten ausführen. Ich möchte diese Parameterwerte und die entsprechenden Funktionsformen "festhalten". Im Folgenden meines Versuch:
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
Jetzt ausführen ich eine Simulation und Buch führen:
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 │
So funktioniert mein Ansatz mit einem Parameterwert, aber nicht mit einer Funktion. Wie kann ich MainModule.#2
durch etwas wie folgt ersetzen?
Option (i)
c -> if γ == 1.0; log(c); else (c^(1-γ)-1)/(1-γ) end,
Option (ii) (Substitution der numerische Wert von γ = 2,0)
(c^(1-2.0)-1)/(1-2.0)
oder eine vereinfachte Version wie 1-c^(-1.0)
Meine Frage bezieht sich auf Julia: show body of function (to find lost code), aber einfacher, da der Körper der Funktion nicht "verloren" ist, sondern in meiner Quelle leicht verfügbar ist.
FYI, [Sugar.jl] (https://github.com/SimonDanisch/Sugar.jl) – Gnimuc
Possible Duplikat [Retrieve Verfahren Inhalt als \ ' Ausdr \ u00fcckung} (https://stackoverflow.com/questions/42514371/retrieve-method-content-as-an- expression) –