Optional positional arguments at the begining

Hello guys I am not a computer scientist and I am new to Julia, I am using Agents.jl for agent-based simulations. I found this function that adds agents and there are multiple signatures for it to exploit the multi dispatch option.

add_agent!([pos,] model::ABM, args...) → newagent
add_agent!([pos,] model::ABM; kwargs...) → newagent

My problem with this is that the optional positional arguments should be at the end and here we see that they are at the beginning ? Any explanation please ?

1 Like

They are optional arguments in the sense that it is optional for the user whether it will provide these or not. Technically speaking they are not “optional positional arguments” in the sense of the function definition f(a, b=0.2) = ....

These optional arguments are achieved via multiple dispatch, by utilizing the fact that the type of this first arugment is special if it is a position input. You can achieve this in julia with something like:

f(a::Real, b::Vector) = a .* b
f(b::Vector) = b

In this way a is an “optional argument” that scales b.

I admit this is a bit weird for a newcomer. Surely in my example above a is an optional argument and is specified by position. So it is an “optional positional argument”. I hope this helps… I don’t know myself how to explain it better :stuck_out_tongue: Let’s hope another senior member attempts at an answer!

6 Likes

Thank you very much now I get it… You explained it very well :+1:

NB: a function definition with an optional argument, like f(mandatory, optional=nothing) = g(mandatory, optional), is really just syntax sugar for:

f(mandatory, optional) = g(mandatory, optional)
f(mandatory) = f(mandatory, nothing)

So the only difference between optional positional arguments at the end versus at the beginning is availability of syntax sugar.

I do sometimes wish it was easier to write optional initial arguments.