I tried to list all the ways one can define functions in Julia. Some are practical, some are silly but collecting them all is fun.
Planning to make a video for fun exploring this.
function name(a, b)
a + b
end
name(a,b) = a + b
if false
name = (a,b) -> a+b
end
name2 = (a,b) -> a+b
name3 = function(a, b)
a+b
end
macro defining_function(fnname)
:(
function $fnname(a, b)
a+b
end
)
end
@defining_function name4
function fn_generator()
function (a, b)
a*b
end
end
name5 = fn_generator()
function fn_generator2()
function name(a, b)
a*b
end
end
# what would happen here?
fn_generator2()
Can we change that? afaik it’s only C++ that calls those “functors” and everywhere else “functors” are a different thing. “Callables” is a good and widely used name.
The last definition of f is used. Some may see this as a bug. To avoid this “behaviour” use anonymous functions instead.
julia> function fn_generator()
if true
f = () -> 0
else
f = (x, y) -> x+y
end
end
fn_generator (generic function with 1 method)
julia> name = fn_generator()
#10 (generic function with 1 method)
julia> name()
0
I don’t see a warning for either version. Can you demonstrate this?
UPDATE:
Ah, I see, the function signature must be the same (it isn’t in the example above):
julia> function fn_generator()
if true
f() = 0
else
f() = 2
end
end
WARNING: Method definition f() in module Main at REPL[1]:3 overwritten at REPL[1]:5.
fn_generator (generic function with 1 method)