I am writing a function factory that takes two functions and weighs them by some _wt
\in (0,1).
function fun_mix(fun1::Function, fun2::Function; _nm_wt="_wt")
f = function (u::AbstractFloat, args...; _wt=0.5)
_wt * fun1(u; args...) + (1 -_wt) * fun2(u; args...)
end
return f
end
Now, I want to allow the user to change the default value of _nm_wt
to be something else, say beta
, so that later the inner function could be called with that new parameter name and not the placeholder name I proposed here.
Essentially I want to capture function f
parse the AST, find all the places where _wt
is used and substitute it with the Symbol(_nm_wt)
. Note, that if I capture the function definition at the time of creation, then I have to capture and substitute the function names fun1
and fun2
and, potentially, all the things they point to, so I would prefer to not mess with that, if possible.
In R, you can capture a function and manipulate its formals and body separately, so I have done it as
fun_mix <- function(fun1, fun2, nm_wt=".wt"){
f <- function(u, .wt=0.5, ...){
(.wt)*fun1(u, ...) + (1-.wt)*fun2(u, ...)
}
formals_ <- formals(f)
body_ <- body(f)
names(formals_)[names(formals_) == ".wt"] <- nm_wt
body_ <- do.call(substitute, list(body_, list(.wt = as.symbol(nm_wt))))
as.function(c(formals_, body_))
}
How do I repeat this success in Julia?