How to define a function inside a function depending on the values ​​of variables

I am writing a function that it would be easier for me to write and read if it could define another function differently depending on the input values ​​or the execution time of the variables (and then use this function). The idea is illustrated below (even if defining a function inside a function does not have an advantage in this simple example):

julia> function f(option::Bool)
           if option
               g() = println("option true")
               g()
           else
               g() = println("option false")
               g()
           end
       end;
WARNING: Method definition g() in module Main at REPL[1]:3 overwritten at REPL[1]:6.

julia> f(true)
option false

julia> f(false)
ERROR: UndefVarError: g not defined
 in f(::Bool) at .\REPL[1]:7

Using the full syntax function... endfor gdoesn't help either.

Question: Am I doing something wrong to get this warning and this is an unintended behavior, or is Julia not allowing this for some reason? And if it can be done, how?

N.B. : g1 g2, , , ; , g ? , , , : , , ..

P.S. , String, , .

+4
1

. ( ).

function f(option::Bool)
           if option
               g = () -> println("option true")
           else
               g = () -> println("option false")
           end
         g
       end

v.5 , . , sytnax :

f = function (x)
    x
end

:

(T::typeof(f))(x,y) = x+y

.

+6

Source: https://habr.com/ru/post/1662885/


All Articles