Redefined functions do not pass correctly as arguments


I’m having trouble with passing redefined functions as arguments of other functions (in my case, constantly redefined objetive functions to a minimizing method). The following behavior is observed in kernels 0.5.0 and 0.6.0-dev but not in 0.4.7 (I’m running a jupyter notebook at

A minimal example is the following:
h(f::Function, n::Int) = f() + n # Define a function taking some arguments f() = 10 # Define a function to be passed as argument h(f,1) # This output 11 correctly

But if now we redefine “f”:
f() = 20 h(f,5) # This output 15!

That is, the function h takes n correctly but not the new function f (it should return 25).
For now, my solution is working on 0.4.7 but I wonder if there is an explanation for this behaviour (I already read this for example, but there is not a clear response).

this is fixed on master

1 Like

On julia v0.5 you can work around issue #265 by making f() an anonymous function instead:

julia> h(f::Function, n::Int) = f() + n
h (generic function with 1 method)

julia> f = () -> 10
(::#1) (generic function with 1 method)

julia> h(f, 1)

julia> f = () -> 20
(::#3) (generic function with 1 method)

julia> h(f, 5)
1 Like

But what if f is a complicated function in which their definition requires non-inline computations?

Anywhere you can place a single expression in Julia, you can also place a block of code using a begin...end block:

julia> f = () -> begin
       println("hello world")
(::#1) (generic function with 1 method)

julia> f()
hello world

Of course, the short answer is, as @yuyichao said, that this fixed in julia master, so this hack won’t be required in the future.

You can still use the function syntax:

julia> f = function(x)
         return x + 1
(::#1) (generic function with 1 method)

julia> f(1)