From this link, it says:
# You can define functions with optional positional arguments
function defaults(a,b,x=5,y=6)
return "$a $b and $x $y"
end
defaults('h','g') # => "h g and 5 6"
defaults('h','g','j') # => "h g and j 6"
defaults('h','g','j','k') # => "h g and j k"
try
defaults('h') # => ERROR: no method defaults(Char,)
defaults() # => ERROR: no methods defaults()
catch e
println(e)
end
I think the purpose of this example is to show that, if the provided arguments are less than the default ones, the function will also return the default ones.
But why the error appears when one or no argument is provided? i.e. how do I know that providing two arguments are okay, but providing one or none is not okay?
The answer is quite simple:
For the function defaults
it is required to give at least two arguments (a
and b
that have no default value), because the language specifications do not allow required positional arguments to be in an "unknown state". If no default value is provided, the interpreter raises the exception. Citing the manual, the design reason behind optional arguments:
Optional arguments are actually just a convenient syntax for writing multiple method definitions with different numbers of arguments
It is like they are creating some "functions" that already knows which are some of the arguments. You write:
defaults(a,b,x=5,y=6)
and internally exist:
defaults(a, b, x, y)
defaults(a, b, x, 6)
defaults(a, b, 5, 6)
(and notice that I'm not writing defaults(a, b, 5, y)
to keep the discussion simple).
Calling defaults
with 3 arguments is ok, but you will override the default value of x
. Calling it with 4 arguments is ok, but you will override the default value of x
and y
. Calling it with less than 2 arguments is not ok, because the interpreter does not know what to return (since you need a
and b
to interpolate the returned string).
You may define a function that will require only one positional argument in this way:
function defaults(a,b=4,x=5,y=6)
return "$a $b and $x $y"
end
There are more information also here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With