Jump to content

Named parameters: Difference between revisions

Added Oz example.
No edit summary
(Added Oz example.)
Line 253:
 
Named arguments can be made optional, with the <code>?(arg = value)</code> syntax in the parameter declaration. See the optional parameters task for more details.
 
=={{header|Oz}}==
For <b>methods</b>, Oz does support named parameters with default values. The named parameters can be freely reordered.
<lang oz>declare
class Foo
meth init skip end
meth bar(PP %% positional parameter
named1:N1
named2:N2
namedWithDefault:NWD <= 42)
{System.showInfo "PP: "#PP#", N1: "#N1#", N2: "#N2#", NWD: "#NWD}
end
end
 
O = {New Foo init}
{O bar(1 named1:2 named2:3 namedWithDefault:4)} %% ok
{O bar(1 named2:2 named1:3)} %% ok
{O bar(1 named1:2)} %% not ok, "missing message feature in object application"</lang>
 
For <b>procedures</b> only positional parameters are supported. However, you can emulate named parameters by using records:
<lang oz>
declare
proc {Foo PP Other=unit(named1:N1 named2:N2 ...)}
NWD = {CondSelect Other namedWithDefault 42}
in
{System.showInfo "PP: "#PP#", N1: "#N1#", N2: "#N2#", NWD: "#NWD}
end
 
{Foo 1 unit(named1:2 named2:3 namedWithDefault:4)}
{Foo 1 unit(named2:2 named1:3)}
{Foo 1 unit(named1:2)} %% not ok...</lang>
 
The procedure Foo is defined with pattern matching in the argument list. The ellipsis means that additional record fields are allowed. To access optional record fields, we have to explicitly try to select a field and provide a default value in case it is missing ("CondSelect").
 
=={{header|Perl}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.