Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia overwriting function before its called

Tags:

function

julia

The easiest way to explain the problem is with a code snippet.

function foo()
  bar(x) = 1+x
  println(bar(1)) #expecting a 2 here
  bar(x) = -100000x
  println(bar(1)) #expecting -100000
end

foo()

OUTPUT:

-100000
-100000

I imagine that the compiler is optimizing away a function that doesn't last long, but I haven't seen anything in the docs that would cause me to expect this behavior, and Google returns nothing but the docs. What is going on here?

like image 768
Trace Avatar asked Dec 23 '22 16:12

Trace


1 Answers

This looks like a version of https://github.com/JuliaLang/julia/issues/15602. In the upcoming Julia 1.6 release this gives a warning:

julia> function foo()
         bar(x) = 1+x
         println(bar(1)) #expecting a 2 here
         bar(x) = -100000x
         println(bar(1)) #expecting -100000
       end
WARNING: Method definition bar(Any) in module Main at REPL[1]:2 overwritten at REPL[1]:4.
foo (generic function with 1 method)

You should use anonymous functions like this instead:

julia> function foo()
         bar = x -> 1+x
         println(bar(1)) #expecting a 2 here
         bar = x -> -100000x
         println(bar(1)) #expecting -100000
       end
foo (generic function with 1 method)

julia> foo()
2
-100000
like image 131
fredrikekre Avatar answered Jan 01 '23 11:01

fredrikekre