Fixing parameter values to create new simpler function

Very new to Julia, so apologies for the naive question. I was wondering if there was a neat way to fix parameter values in a function, to create a new simpler function. The reason I want to do this is because certain optimizers/algorithms don’t seem to allow “extra” arguments/hyperparameters that aren’t being optimized.

I am more familiar with R. A pattern often used in R is a function factory pattern, which in Julia is something like:

function my_fun(;θ1=1, θ2=1, constant1=1, constant2=1)
    return θ1 + θ2 + constant1 + constant2

func_factory = function(constant1, constant2)
    new_func = function(θ1=1, θ2=1)
        return my_fun(θ1, θ2, constant1, constant2)
    return new_func

new_func = func_factory(1,2)

I was wondering if this is OK, and if there was a neater/better way to do it? I guess the end result in an ideal world would be something that worked for any function as follows:

kwargs_to_fix = (kwargname1=1, kwargname2=1)
new_func = func_factory(my_func, kwargs_to_fix)

What would be the best way to achieve this?

Something like

julia> function my_func(;θ1=1, θ2=1, constant1=1, constant2=1)
           return θ1 + θ2 + constant1 + constant2
my_func (generic function with 1 method)

julia> kwargs_to_fix = (constant1=221, constant2=112)
(constant1 = 221, constant2 = 112)

julia> new_func(args...; kwargs...) = my_func(args...; kwargs..., kwargs_to_fix...)
new_func (generic function with 1 method)

julia> new_func(θ1=5, θ2=3)


1 Like

Thanks, that seems to work quite well. My one minor issue with I have with this is the lack of typing hints in the generated function.