# https://docs.julialang.org/en/stable/manual/methods/#man-note-on-optional-and-keyword-arguments
# Optional args are implemented as syntax for multiple method definitions, e.g.
f(a=1,b=2) = a+2b
# which translates into three methods
f(a,b) = a+2b # explicit/optional a,b args
f(a) = f(a,2) # explicit/optional a arg
f() = f(1,2) # no optional args, f() call equivalent to f(1,2) call, which invokes f(a,b) and results to 5
I’m assuming method f(b) = f(1,2b) is implicit here? How do I call it? E.g. f(,8) didn’t work. @yuyichao@Michael_Eastwood
Oh I wasn’t planning on overwriting anything, just trying to understand how optional args and their methods work. So optional args can only be called all at once, none at all, or from the first positional argument a. You can’t call more than one optional arg from say a tuple of five args. That’s my understanding and I don’t know the criteria for that decision.
Presumably, it’s just a simple enough implementation of that concept. If you have more than 1 or 2 optional arguments, you should probably be using keyword arguments anyway.
julia> f(a="default", b="default", c="default", d="default") = @show a b c d
f (generic function with 5 methods)
julia> f("not the default", "not the default", "not the default", "not the default");
a = "not the default"
b = "not the default"
c = "not the default"
d = "not the default"
julia> f("not the default", "not the default", "not the default");
a = "not the default"
b = "not the default"
c = "not the default"
d = "default"
julia> f("not the default", "not the default");
a = "not the default"
b = "not the default"
c = "default"
d = "default"
julia> f("not the default");
a = "not the default"
b = "default"
c = "default"
d = "default"
julia> f();
a = "default"
b = "default"
c = "default"
d = "default"
julia> f(a="default",d="default"; b="default",c="default") = @show a b c d
f (generic function with 3 methods) # b and c are keyword args
julia> f(b="not default", c="not default");
a = "default"
b = "not default"
c = "not default"
d = "default"
You can only do that using keyword arguments. f uses only positional arguments and when using positional arguments, you can only give as input to the function the first k arguments with the last n-k arguments being the default values.
That’s even better, thanks! Then there’s no point in using keyword args. Just place all optionals at the beginning or end of list
julia> f( b="default",a="default", d="default",c="default") = @show a b c d
f (generic function with 5 methods)
julia> f(b="not default", c="not default");
a = "default"
b = "not default"
c = "not default"
d = "default"