Declaring the name of argument when invoking a function

Viewed 683

In Julia 1.4.0 I have the following function:

function output(W::Int64,F::Int64,P::Int64,S::Int64)
       return ((W-F+2*P)/S +1)
       end

When I enter the following command, the output is as expected

julia> output(28,5,0,1)
24.0

Now, in order to be sure which argument is what, I what to explicitly name them when invoking the function (which could be helpful if one could write the argument in a different order if it is possible)

julia> output(W=28,F=5,P=0,S=1)
ERROR: MethodError: no method matching output(; W=28, F=5, P=0, S=1)
Closest candidates are:
  output(::Int64, ::Int64, ::Int64, ::Int64) at REPL[23]:2 got unsupported keyword arguments "W", "F", "P", "S"
  output(::Any, ::Any, ::Any, ::Any) at REPL[2]:2 got unsupported keyword arguments "W", "F", "P", "S"
Stacktrace:
 [1] top-level scope at REPL[25]:1

Is an other similar approach possible?

1 Answers

You want to use keyword arguments for your function (you can read more about keyword arguments in the Julia docs)

To declare your function with keyword arguments you should do this (note the semi-colon before the arguments):

function output(;W::Int64,F::Int64,P::Int64,S::Int64)
       return ((W-F+2*P)/S +1)
end

Then, you can run your function as you wanted:

julia> output(W=28,F=5,P=0,S=1)
24.0
Related