Passing Some Arguments To A Function That Is An Argument To Some Other Function

Hello,

I am wondering whether there is a nice way of passing arguments to a function that is itself an argument to a function. So, currently, I have a piece of code that looks like this:

function func_manip(func)
    # Uses the function in some way
end

function linear_func(x, a)
    return x*a
end

for i in 0:10
    f(x) = linear_func(x, i)
    func_manip(f)
end

My guts tells me that this is not the most elegant way of doing this. I was thinking that maybe there would be a way of doing something where instead of defining the f function, I could simply specify which arguments I pass with the inputted function in func_manip. So something like:

function func_manip(func)
    # Uses the function in some way
end

function linear_func(x, a)
    return x*a
end

for i in 0:10
    func_manip(f(::, i))
end

Otherwise, I thought about adding another argument to the func_manip that I would be plugging into func inside func_manip, but for the precise application I was working on, it was making the code a bit crowded. Maybe there is another method that essentially does the same thing.
Any help is appreciated!

1 Like

An anonymous function works very nicely in this case:

julia> function func_manip(func)
           @show func(1)
       end
func_manip (generic function with 1 method)

julia> function linear_func(x, a)
           return x*a
       end
linear_func (generic function with 1 method)

julia> for i in 0:10
           func_manip(x -> linear_func(x, i))
       end

where x -> linear_func(x, i) creates a new function of one variable and closes over the variable i (a.k.a a closure).

6 Likes

I like that! Thanks!