Named parameters: Difference between revisions

Content added Content deleted
(Add a Tcl example using dicts)
m (syntax highlighting fixup automation)
Line 16: Line 16:
=={{header|11l}}==
=={{header|11l}}==


<lang 11l>F sqlen(x = 0, y = 0, z = 0)
<syntaxhighlight lang="11l">F sqlen(x = 0, y = 0, z = 0)
R x*x + y*y + z*z
R x*x + y*y + z*z


print(sqlen(z' 3)) // equivalent to print(sqlen(0, 0, 3))</lang>
print(sqlen(z' 3)) // equivalent to print(sqlen(0, 0, 3))</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
All callable entities (procedures, functions, entries) require named arguments. All of them can be called using either positional or keyed association of the actual arguments. The arguments supplied with default values can be omitted.
All callable entities (procedures, functions, entries) require named arguments. All of them can be called using either positional or keyed association of the actual arguments. The arguments supplied with default values can be omitted.
<lang Ada>procedure Foo (Arg_1 : Integer; Arg_2 : Float := 0.0);</lang>
<syntaxhighlight lang="ada">procedure Foo (Arg_1 : Integer; Arg_2 : Float := 0.0);</syntaxhighlight>
It can be equivalently called as:
It can be equivalently called as:
<lang Ada>Foo (1, 0.0);
<syntaxhighlight lang="ada">Foo (1, 0.0);
Foo (1);
Foo (1);
Foo (Arg_2 => 0.0, Arg_1 => 1);
Foo (Arg_2 => 0.0, Arg_1 => 1);
Foo (Arg_1 => 1);</lang>
Foo (Arg_1 => 1);</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{trans|Lua}}
{{trans|Lua}}
<lang algol68>BEGIN
<syntaxhighlight lang="algol68">BEGIN
MODE OPTNAME = STRUCT(STRING name),
MODE OPTNAME = STRUCT(STRING name),
OPTSPECIES = STRUCT(STRING species),
OPTSPECIES = STRUCT(STRING species),
Line 67: Line 67:
print pet((NAME "Mike", SPECIES "Dog", BREED "Irish Setter", OWNER("Harry", "S.", "Truman")));
print pet((NAME "Mike", SPECIES "Dog", BREED "Irish Setter", OWNER("Harry", "S.", "Truman")));
print pet(()) # use print pet((EMPTY)) for Algol 68G version 2 #
print pet(()) # use print pet((EMPTY)) for Algol 68G version 2 #
END</lang>
END</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 76: Line 76:
=={{header|AppleScript}}==
=={{header|AppleScript}}==
AppleScript does not implement default or optional parameters, but they can be simulated using records.
AppleScript does not implement default or optional parameters, but they can be simulated using records.
<lang AppleScript>on getName(x)
<syntaxhighlight lang="applescript">on getName(x)
set {firstName, lastName} to {"?", "?"}
set {firstName, lastName} to {"?", "?"}
try
try
Line 86: Line 86:


return firstName & ", " & lastName
return firstName & ", " & lastName
end getName</lang>
end getName</syntaxhighlight>
Examples:
Examples:
<lang AppleScript >getName({firstName:"John", lastName:"Doe"})
<syntaxhighlight lang="applescript ">getName({firstName:"John", lastName:"Doe"})
--> Returns: "John, Doe"
--> Returns: "John, Doe"
getName({lastName:"Doe"})
getName({lastName:"Doe"})
--> Returns: "?, Doe"</lang>
--> Returns: "?, Doe"</syntaxhighlight>
----
----
An easier way to achieve the above is by concatenating a record containing default values for the expected properties to the record actually passed. The result will contain the labels and values from both records, except that where the same label exists in both records, there'll only be one instance in the result and its value will be that from the first record:
An easier way to achieve the above is by concatenating a record containing default values for the expected properties to the record actually passed. The result will contain the labels and values from both records, except that where the same label exists in both records, there'll only be one instance in the result and its value will be that from the first record:


<lang applescript>on getName(x) -- x assumed to be a record for this demo.
<syntaxhighlight lang="applescript">on getName(x) -- x assumed to be a record for this demo.
set x to x & {firstName:"?", lastName:"?"}
set x to x & {firstName:"?", lastName:"?"}


Line 102: Line 102:


getName({lastName:"Doe"})
getName({lastName:"Doe"})
--> "?, Doe"</lang>
--> "?, Doe"</syntaxhighlight>


One of AppleScript's handler types has long been "handlers with labeled parameters". These haven't proved particularly popular as they have a limited set of AppleScript-defined labels, which can require some creativity when choosing one to make sense in the script narrative. However, labelled parameters can be given in any order in calls:
One of AppleScript's handler types has long been "handlers with labeled parameters". These haven't proved particularly popular as they have a limited set of AppleScript-defined labels, which can require some creativity when choosing one to make sense in the script narrative. However, labelled parameters can be given in any order in calls:


<lang applescript>on getName from firstName beside lastName
<syntaxhighlight lang="applescript">on getName from firstName beside lastName
return firstName & ", " & lastName
return firstName & ", " & lastName
end getName
end getName


getName beside "Doe" from "John"
getName beside "Doe" from "John"
--> "John, Doe"</lang>
--> "John, Doe"</syntaxhighlight>


However, it's also possible to define user labels, with the same flexibility of order, using a slightly different syntax:
However, it's also possible to define user labels, with the same flexibility of order, using a slightly different syntax:


<lang applescript>on getName given firstName:firstName, lastName:lastName
<syntaxhighlight lang="applescript">on getName given firstName:firstName, lastName:lastName
return firstName & ", " & lastName
return firstName & ", " & lastName
end getName
end getName


getName given lastName:"Doe", firstName:"John"
getName given lastName:"Doe", firstName:"John"
--> "John, Doe"</lang>
--> "John, Doe"</syntaxhighlight>


AppleScript-defined and user labels can be combined, but the AppleScript ones must be given first if used. The <tt>given</tt> syntax also has a neat feature whereby if the value to be passed is a boolean, the keyword <tt>with</tt> or <tt>without</tt> can be used instead in the call. In fact the compiler imposes this anyway when a boolean is hard-coded into the call:
AppleScript-defined and user labels can be combined, but the AppleScript ones must be given first if used. The <tt>given</tt> syntax also has a neat feature whereby if the value to be passed is a boolean, the keyword <tt>with</tt> or <tt>without</tt> can be used instead in the call. In fact the compiler imposes this anyway when a boolean is hard-coded into the call:


<lang applescript>on getName given firstName:firstName, lastName:lastName, comma:comma
<syntaxhighlight lang="applescript">on getName given firstName:firstName, lastName:lastName, comma:comma
if (comma) then
if (comma) then
return firstName & ", " & lastName
return firstName & ", " & lastName
Line 135: Line 135:
--> "John, Doe"
--> "John, Doe"
getName without comma given lastName:"Doe", firstName:"John"
getName without comma given lastName:"Doe", firstName:"John"
--> "John Doe"</lang>
--> "John Doe"</syntaxhighlight>


Since Mac OS X 10.10, it ''has'' been possible to make labelled parameters optional by defining default values for them in the handler declarations. But at least one parameter must be provided in any call:
Since Mac OS X 10.10, it ''has'' been possible to make labelled parameters optional by defining default values for them in the handler declarations. But at least one parameter must be provided in any call:


<lang applescript>use AppleScript version "2.4" -- Mac OS X 10.10 (Yosemite) or later.
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- Mac OS X 10.10 (Yosemite) or later.


on getName under category : "Misc: " given firstName:firstName : "?", lastName:lastName : "?", comma:comma : true
on getName under category : "Misc: " given firstName:firstName : "?", lastName:lastName : "?", comma:comma : true
Line 150: Line 150:


getName given lastName:"Doe"
getName given lastName:"Doe"
--> "Misc: ?, Doe"</lang>
--> "Misc: ?, Doe"</syntaxhighlight>


=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
Function definitions in Applesoft BASIC using the DEF FN statement can only have one parameter. Subroutines and functions with many parameters can be simulated using global variables which are effectively named parameters. Default or optional parameters can be simulated with a check in the subroutine.
Function definitions in Applesoft BASIC using the DEF FN statement can only have one parameter. Subroutines and functions with many parameters can be simulated using global variables which are effectively named parameters. Default or optional parameters can be simulated with a check in the subroutine.


<lang ApplesoftBasic> 100 IF LAST$ = "" THEN PRINT "?";
<syntaxhighlight lang="applesoftbasic"> 100 IF LAST$ = "" THEN PRINT "?";
110 IF LAST$ < > "" THEN PRINT LAST$;
110 IF LAST$ < > "" THEN PRINT LAST$;
120 IF FIRST$ < > "" THEN PRINT ", "FIRST$;
120 IF FIRST$ < > "" THEN PRINT ", "FIRST$;
200 FIRST$ = ""
200 FIRST$ = ""
210 LAST$ = ""
210 LAST$ = ""
220 RETURN</lang>
220 RETURN</syntaxhighlight>


<pre>]FIRST$ = "JOHN" : GOSUB 100"PRINT NAME
<pre>]FIRST$ = "JOHN" : GOSUB 100"PRINT NAME
Line 171: Line 171:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>func: function [x][
<syntaxhighlight lang="rebol">func: function [x][
print ["argument x:" x]
print ["argument x:" x]
print ["attribute foo:" attr 'foo]
print ["attribute foo:" attr 'foo]
Line 182: Line 182:
func .bar:"bar" 3
func .bar:"bar" 3
func .foo:123 .bar:124 4
func .foo:123 .bar:124 4
func .bar:124 .foo:123 5</lang>
func .bar:124 .foo:123 5</syntaxhighlight>


{{out}}
{{out}}
Line 209: Line 209:
AutoHotkey doesn't have named parameters, but they can be simulated as follows.
AutoHotkey doesn't have named parameters, but they can be simulated as follows.
ahk [http://www.autohotkey.com/forum/viewtopic.php?p=280499 discussion]
ahk [http://www.autohotkey.com/forum/viewtopic.php?p=280499 discussion]
<lang AutoHotkey>MyFunc( "Val=0, w=1024, Text=The Quick Brown Fox, newVar=I'm New" )
<syntaxhighlight lang="autohotkey">MyFunc( "Val=0, w=1024, Text=The Quick Brown Fox, newVar=I'm New" )


MyFunc( _overrides="" ) {
MyFunc( _overrides="" ) {
Line 220: Line 220:
Listvars
Listvars
WinWaitClose, %A_ScriptFullPath%
WinWaitClose, %A_ScriptFullPath%
}</lang>
}</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
In Bracmat, all functions have exactly one argument, called "arg". To split the argument and assign values to local variables, you always have to use pattern matching.
In Bracmat, all functions have exactly one argument, called "arg". To split the argument and assign values to local variables, you always have to use pattern matching.
In this task, the pattern is just made a bit more complex than would have been the case without explicit parameter names in the argument.
In this task, the pattern is just made a bit more complex than would have been the case without explicit parameter names in the argument.
<lang bracmat>( ( testproc
<syntaxhighlight lang="bracmat">( ( testproc
= i x y z
= i x y z
. out$"Calling testproc"
. out$"Calling testproc"
Line 244: Line 244:
& testproc$((z,4) (x,2) (y,3)) { order is not important }
& testproc$((z,4) (x,2) (y,3)) { order is not important }
& testproc$((i,1) (y,2) (z,3))
& testproc$((i,1) (y,2) (z,3))
);</lang>
);</syntaxhighlight>
Output:
Output:
<pre>Calling testproc
<pre>Calling testproc
Line 260: Line 260:
{{works with|C99}}
{{works with|C99}}


<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


// 1. Named parameters
// 1. Named parameters
Line 307: Line 307:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


As a bonus, default values for the parameters left unspecified can be either implicitly set to zero by the struct initializer, or supplied in a wrapper-macro definition. But this is not idiomatic C by any stretch.
As a bonus, default values for the parameters left unspecified can be either implicitly set to zero by the struct initializer, or supplied in a wrapper-macro definition. But this is not idiomatic C by any stretch.
Line 317: Line 317:
Named parameters were added in C# 4.0. The examples below demonstrate how named parameters and optional parameters are a single concept in the language.
Named parameters were added in C# 4.0. The examples below demonstrate how named parameters and optional parameters are a single concept in the language.


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


namespace NamedParams
namespace NamedParams
Line 336: Line 336:
}
}
}
}
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 350: Line 350:
You wrap the parameters in a class, and make the function a friend of the parameter class.
You wrap the parameters in a class, and make the function a friend of the parameter class.


<lang cpp>class foo_params{
<syntaxhighlight lang="cpp">class foo_params{
friend void foo(foo_params p);
friend void foo(foo_params p);
public:
public:
Line 376: Line 376:
int optional_y_;
int optional_y_;
float optional_z_;
float optional_z_;
};</lang>
};</syntaxhighlight>


Declare the function to take the parameter class as its only parameter.
Declare the function to take the parameter class as its only parameter.


<lang cpp>void foo(foo_params p){ . . .}</lang>
<syntaxhighlight lang="cpp">void foo(foo_params p){ . . .}</syntaxhighlight>


Call the function using the parameter object constructor with the required parameters and chaining the optional parameters.
Call the function using the parameter object constructor with the required parameters and chaining the optional parameters.


<lang cpp>foo(foo_params(42).x(7).z(23.54));</lang>
<syntaxhighlight lang="cpp">foo(foo_params(42).x(7).z(23.54));</syntaxhighlight>




Line 390: Line 390:


If you want real named parameters you can use The Boost Parameter Library.
If you want real named parameters you can use The Boost Parameter Library.
<lang cpp>#include <boost/parameter/name.hpp>
<syntaxhighlight lang="cpp">#include <boost/parameter/name.hpp>
#include <boost/parameter/preprocessor.hpp>
#include <boost/parameter/preprocessor.hpp>
#include <string>
#include <string>
Line 415: Line 415:
if (baz && (bar > 1.0)) return foo;
if (baz && (bar > 1.0)) return foo;
return bonk.size();
return bonk.size();
}</lang>
}</syntaxhighlight>


Once the definition is written, using it is easy, by name or position.
Once the definition is written, using it is easy, by name or position.


<lang cpp>function_with_named_parameters(1, 10.0);
<syntaxhighlight lang="cpp">function_with_named_parameters(1, 10.0);
function_with_named_parameters(7, _bar = 3.14);
function_with_named_parameters(7, _bar = 3.14);
function_with_named_parameters( _bar = 0.0, _foo = 42);
function_with_named_parameters( _bar = 0.0, _foo = 42);
function_with_named_parameters( _bar = 2.5, _bonk= "Hello", _foo = 9);
function_with_named_parameters( _bar = 2.5, _bonk= "Hello", _foo = 9);
function_with_named_parameters(9, 2.5, true, "Hello");</lang>
function_with_named_parameters(9, 2.5, true, "Hello");</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
Line 429: Line 429:
Clojure doesn't have built-in support for named or keyword arguments, but you can use destructuring to achieve a similar effect.
Clojure doesn't have built-in support for named or keyword arguments, but you can use destructuring to achieve a similar effect.


<lang clojure>(defn foo [& opts]
<syntaxhighlight lang="clojure">(defn foo [& opts]
(let [opts (merge {:bar 1 :baz 2} (apply hash-map opts))
(let [opts (merge {:bar 1 :baz 2} (apply hash-map opts))
{:keys [bar baz]} opts]
{:keys [bar baz]} opts]
[bar baz]))</lang>
[bar baz]))</syntaxhighlight>


Clojure 1.2 supports destructuring of trailing arguments as a map:
Clojure 1.2 supports destructuring of trailing arguments as a map:


<lang clojure>(defn foo [& {:keys [bar baz] :or {bar 1, baz 2}}]
<syntaxhighlight lang="clojure">(defn foo [& {:keys [bar baz] :or {bar 1, baz 2}}]
[bar baz])</lang>
[bar baz])</syntaxhighlight>


You can also use <code>defnk</code> from <code>clojure.contrib.def</code>, which is a macro that works similarly.
You can also use <code>defnk</code> from <code>clojure.contrib.def</code>, which is a macro that works similarly.


<lang clojure>(use 'clojure.contrib.def)
<syntaxhighlight lang="clojure">(use 'clojure.contrib.def)
(defnk foo [:bar 1 :baz 2]
(defnk foo [:bar 1 :baz 2]
[bar baz])</lang>
[bar baz])</syntaxhighlight>


Sample output for all variants:
Sample output for all variants:
Line 457: Line 457:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==


<lang lisp>(defun print-name (&key first (last "?"))
<syntaxhighlight lang="lisp">(defun print-name (&key first (last "?"))
(princ last)
(princ last)
(when first
(when first
(princ ", ")
(princ ", ")
(princ first))
(princ first))
(values))</lang>
(values))</syntaxhighlight>


<code>&key</code> indicates that further parameters are named (keyword parameters); a bare symbol (e.g. <var>first</var>) has a default of NIL, whereas a list (e.g. <code>(<var>last</var> "?")</code>) gives the variable name and the default value (which is evaluated when the function is called, unlike Python).
<code>&key</code> indicates that further parameters are named (keyword parameters); a bare symbol (e.g. <var>first</var>) has a default of NIL, whereas a list (e.g. <code>(<var>last</var> "?")</code>) gives the variable name and the default value (which is evaluated when the function is called, unlike Python).


<lang lisp>CL-USER> (print-name)
<syntaxhighlight lang="lisp">CL-USER> (print-name)
?
?
CL-USER> (print-name :first "John")
CL-USER> (print-name :first "John")
Line 473: Line 473:
Doe, John
Doe, John
CL-USER> (print-name :last "Doe")
CL-USER> (print-name :last "Doe")
Doe</lang>
Doe</syntaxhighlight>


In Common Lisp, the arguments to a function are always a simple list of values; the <code>&key</code> facility merely defines an interpretation of that list by the function: alternating keys and values. (As a result of this, mixing [[varargs]] (<code>&rest</code>) with named parameters is not recommended as it requires some additional means of distinguishing them. On the other hand, functions which pass their arguments on to other functions need not handle named arguments distinctly.)
In Common Lisp, the arguments to a function are always a simple list of values; the <code>&key</code> facility merely defines an interpretation of that list by the function: alternating keys and values. (As a result of this, mixing [[varargs]] (<code>&rest</code>) with named parameters is not recommended as it requires some additional means of distinguishing them. On the other hand, functions which pass their arguments on to other functions need not handle named arguments distinctly.)
Line 483: Line 483:
{{Trans|C++}}
{{Trans|C++}}
Delphi not support named params in any version, this is a uneficient, but functional, adaptation of c++ answer.
Delphi not support named params in any version, this is a uneficient, but functional, adaptation of c++ answer.
<syntaxhighlight lang="delphi">
<lang Delphi>
program Named_parameters;
program Named_parameters;


Line 538: Line 538:


{$IFNDEF UNIX} readln; {$ENDIF}
{$IFNDEF UNIX} readln; {$ENDIF}
end.</lang>
end.</syntaxhighlight>


=={{header|Dyalect}}==
=={{header|Dyalect}}==
Line 544: Line 544:
Dyalect supports both named and optional parameters.
Dyalect supports both named and optional parameters.


<lang dyalect>func fun(x, y = 0, z = 12.2, dsc = "Useless text") {
<syntaxhighlight lang="dyalect">func fun(x, y = 0, z = 12.2, dsc = "Useless text") {
print("x=\(x), y=\(y), z=\(z), dsc=\(dsc)")
print("x=\(x), y=\(y), z=\(z), dsc=\(dsc)")
}
}


fun(12, z: 24.4, dsc: "Foo", y: 3)
fun(12, z: 24.4, dsc: "Foo", y: 3)
fun(y: 42, x: 12)</lang>
fun(y: 42, x: 12)</syntaxhighlight>


{{out}}
{{out}}
Line 560: Line 560:
Since E supports arbitrary pattern matching (in the sense of [[Pattern Matching]] in parameter lists, a map-pattern can be used to provide named parameters, though the syntax is sufficiently noisy that this is not used casually.
Since E supports arbitrary pattern matching (in the sense of [[Pattern Matching]] in parameter lists, a map-pattern can be used to provide named parameters, though the syntax is sufficiently noisy that this is not used casually.


<lang e>def printName([=> first := null, => last := null]) {
<syntaxhighlight lang="e">def printName([=> first := null, => last := null]) {
if (last == null) {
if (last == null) {
print("?")
print("?")
Line 570: Line 570:
print(first)
print(first)
}
}
}</lang>
}</syntaxhighlight>


(Note: In map literals and map patterns, “<code>=> <var>x</var></code>” is shorthand for “<code>"<var>x</var>" => <var>x</var></code>”.)
(Note: In map literals and map patterns, “<code>=> <var>x</var></code>” is shorthand for “<code>"<var>x</var>" => <var>x</var></code>”.)


<lang e>? printName(["first" => "John"])
<syntaxhighlight lang="e">? printName(["first" => "John"])
?, John
?, John


Line 581: Line 581:


? printName(["first" => "John", "last" => "Doe"])
? printName(["first" => "John", "last" => "Doe"])
Doe, John</lang>
Doe, John</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
Line 587: Line 587:
The easiest and visually most appealing way to have named parameters is using a proplist as last parameter of the function.
The easiest and visually most appealing way to have named parameters is using a proplist as last parameter of the function.


<syntaxhighlight lang="elixir">
<lang Elixir>
def fun(bar: bar, baz: baz), do: IO.puts "#{bar}, #{baz}."
def fun(bar: bar, baz: baz), do: IO.puts "#{bar}, #{baz}."


fun(bar: "bar", baz: "baz")
fun(bar: "bar", baz: "baz")
</syntaxhighlight>
</lang>


For this way to use them, order matters, as well as you can't define default values for arguments.
For this way to use them, order matters, as well as you can't define default values for arguments.
Line 597: Line 597:
=={{header|Erlang}}==
=={{header|Erlang}}==
At a guess "named parameters" are supposed to be used like proplists in Erlang.
At a guess "named parameters" are supposed to be used like proplists in Erlang.
<syntaxhighlight lang="erlang">
<lang Erlang>
Fun = fun( Proplists ) ->
Fun = fun( Proplists ) ->
Argument1 = proplists:get_value( argument1, Proplists, 1 ),
Argument1 = proplists:get_value( argument1, Proplists, 1 ),
Line 603: Line 603:
io:fwrite( "~p ~s~n", [Argument1, Kalle] )
io:fwrite( "~p ~s~n", [Argument1, Kalle] )
end.
end.
</syntaxhighlight>
</lang>


The function can now be called like these examples.
The function can now be called like these examples.
Line 619: Line 619:
Named parameters in Factor are as simple as changing the <code>:</code> word to <code>::</code> and using the variables defined in the stack effect declaration.
Named parameters in Factor are as simple as changing the <code>:</code> word to <code>::</code> and using the variables defined in the stack effect declaration.


<syntaxhighlight lang="factor">
<lang Factor>
:: my-named-params ( a b -- c ) a b * ;
:: my-named-params ( a b -- c ) a b * ;
</syntaxhighlight>
</lang>


=={{header|Forth}}==
=={{header|Forth}}==
Line 629: Line 629:


{{works with|Gforth}}
{{works with|Gforth}}
<lang forth>256 buffer: first-name
<syntaxhighlight lang="forth">256 buffer: first-name
256 buffer: last-name
256 buffer: last-name
: is ( a "name" -- ) parse-name rot place ;
: is ( a "name" -- ) parse-name rot place ;
Line 649: Line 649:
cr ." Hiya, " given-name $. space surname $. ." !" ;
cr ." Hiya, " given-name $. space surname $. ." !" ;


Person new >o s" Bob" given-name $! s" Hall" surname $! hiya o></lang>
Person new >o s" Bob" given-name $! s" Hall" surname $! hiya o></syntaxhighlight>


{{out}}<pre>Hello, Bob Hall!
{{out}}<pre>Hello, Bob Hall!
Line 659: Line 659:
Fortran accepts named parameter and optional parameter. Arguments are always named: if the name is omitted, the order used in the definition of the function / subroutine must be used.
Fortran accepts named parameter and optional parameter. Arguments are always named: if the name is omitted, the order used in the definition of the function / subroutine must be used.


<lang fortran>subroutine a_sub(arg1, arg2, arg3)
<syntaxhighlight lang="fortran">subroutine a_sub(arg1, arg2, arg3)
integer, intent(in) :: arg1, arg2
integer, intent(in) :: arg1, arg2
integer, intent(out), optional :: arg3
integer, intent(out), optional :: arg3
! ...
! ...
end subroutine a_sub</lang>
end subroutine a_sub</syntaxhighlight>


<lang fortran>! usage
<syntaxhighlight lang="fortran">! usage
integer :: r
integer :: r
call a_sub(1,2, r)
call a_sub(1,2, r)
call a_sub(arg2=2, arg1=1)</lang>
call a_sub(arg2=2, arg1=1)</syntaxhighlight>


The presence of an optional argument can be tested with <tt>PRESENT</tt>; if optional arguments come before a non optional argument, the usage of the name of the argument is mandatory.
The presence of an optional argument can be tested with <tt>PRESENT</tt>; if optional arguments come before a non optional argument, the usage of the name of the argument is mandatory.


<lang fortran>subroutine b_sub(arg1, arg2)
<syntaxhighlight lang="fortran">subroutine b_sub(arg1, arg2)
integer, intent(in), optional :: arg1
integer, intent(in), optional :: arg1
integer, intent(in) :: arg2
integer, intent(in) :: arg2
!...
!...
end subroutine b_sub</lang>
end subroutine b_sub</syntaxhighlight>


<lang fortran>call b_sub(1) ! error: missing non optional arg2
<syntaxhighlight lang="fortran">call b_sub(1) ! error: missing non optional arg2
call b_sub(arg2=1) ! ok
call b_sub(arg2=1) ! ok
call b_sub(1, 2) ! ok: arg1 is 1, arg2 is 2
call b_sub(1, 2) ! ok: arg1 is 1, arg2 is 2
call b_sub(arg2=2, arg1=1) ! the same as the previous line</lang>
call b_sub(arg2=2, arg1=1) ! the same as the previous line</syntaxhighlight>




=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
{{trans|Visual Basic}}
{{trans|Visual Basic}}
<lang freebasic>Dim Shared foo As Long, bar As Integer, baz As Byte, qux As String
<syntaxhighlight lang="freebasic">Dim Shared foo As Long, bar As Integer, baz As Byte, qux As String
'la función
'la función
Sub LoqueSea(foo As Long, bar As Integer, baz As Byte, qux As String)
Sub LoqueSea(foo As Long, bar As Integer, baz As Byte, qux As String)
Line 695: Line 695:
Sub Algo()
Sub Algo()
LoqueSea(bar = 1, baz = 2, foo = -1, qux = "Probando")
LoqueSea(bar = 1, baz = 2, foo = -1, qux = "Probando")
End Sub</lang>
End Sub</syntaxhighlight>




Line 704: Line 704:


Here's a simple example.
Here's a simple example.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 723: Line 723:
t := myFunc(params{y: 2}) // only one field, others set to zero
t := myFunc(params{y: 2}) // only one field, others set to zero
fmt.Println("t =", t)
fmt.Println("t =", t)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 735: Line 735:
We can simulate named, but not moveable arguments, with nullary data constructors:
We can simulate named, but not moveable arguments, with nullary data constructors:


<lang Haskell>data X = X
<syntaxhighlight lang="haskell">data X = X
data Y = Y
data Y = Y
data Point = Point Int Int deriving Show
data Point = Point Int Int deriving Show
Line 742: Line 742:
createPointAt X x Y y = Point x y
createPointAt X x Y y = Point x y


main = print $ createPointAt X 5 Y 3</lang>
main = print $ createPointAt X 5 Y 3</syntaxhighlight>


We can also emulate named, moveable, optional arguments with record syntax:
We can also emulate named, moveable, optional arguments with record syntax:


<lang Haskell>data Point = Point {x, y :: Int} deriving Show
<syntaxhighlight lang="haskell">data Point = Point {x, y :: Int} deriving Show
defaultPoint = Point {x = 0, y = 0}
defaultPoint = Point {x = 0, y = 0}


createPointAt :: Point -> Point
createPointAt :: Point -> Point
createPointAt = id
createPointAt = id
main = print $ createPointAt (defaultPoint { y = 3, x = 5 })</lang>
main = print $ createPointAt (defaultPoint { y = 3, x = 5 })</syntaxhighlight>


Though this is cumbersome without using template Haskell, as the call site must supply the defaults.
Though this is cumbersome without using template Haskell, as the call site must supply the defaults.
Line 764: Line 764:




<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
testproc("x:=",1,"y:=",2,"z:=",3)
testproc("x:=",1,"y:=",2,"z:=",3)
testproc("x:=",3,"y:=",1,"z:=",2)
testproc("x:=",3,"y:=",1,"z:=",2)
Line 783: Line 783:
write(" y:=",y)
write(" y:=",y)
write(" z:=",z)
write(" z:=",z)
end</lang>
end</syntaxhighlight>
{{improve|Icon|there is currently a bug in Icon that causes assignments via variable("x") to fail for local and static variables. Remove this when this is fixed. The bug does not appear in Unicon.}}
{{improve|Icon|there is currently a bug in Icon that causes assignments via variable("x") to fail for local and static variables. Remove this when this is fixed. The bug does not appear in Unicon.}}


Line 805: Line 805:
J is similar to Perl in that all arguments to functions come in as separate elements in an array. But it is possible to emulate more complex calling conventions. For example, using the [http://www.jsoftware.com/svn/DanBron/trunk/environment/calling_convention.ijs calling convention J script], one could write:
J is similar to Perl in that all arguments to functions come in as separate elements in an array. But it is possible to emulate more complex calling conventions. For example, using the [http://www.jsoftware.com/svn/DanBron/trunk/environment/calling_convention.ijs calling convention J script], one could write:


<lang j>NB. Strand notation
<syntaxhighlight lang="j">NB. Strand notation
myFunc['c:\file.txt' 906 'blue' fs]
myFunc['c:\file.txt' 906 'blue' fs]


Line 830: Line 830:


NB. Even the delimiters are flexible...
NB. Even the delimiters are flexible...
myFunc<MAX=906, COLOR=blue fs></lang>
myFunc<MAX=906, COLOR=blue fs></syntaxhighlight>


For further discussion, see the [http://www.jsoftware.com/pipermail/programming/2009-July/015571.html corresponding thread in the J Forums].
For further discussion, see the [http://www.jsoftware.com/pipermail/programming/2009-July/015571.html corresponding thread in the J Forums].
Line 836: Line 836:
=={{header|Java}}==
=={{header|Java}}==
Like C++, Java also does not support named parameters. Named parameters can however be simulated simply with the "Builder pattern". ([http://drdobbs.com/java/208403883?pgno=2 Joshua Bloch: Builder Pattern])
Like C++, Java also does not support named parameters. Named parameters can however be simulated simply with the "Builder pattern". ([http://drdobbs.com/java/208403883?pgno=2 Joshua Bloch: Builder Pattern])
<lang java>processNutritionFacts(new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build());</lang>
<syntaxhighlight lang="java">processNutritionFacts(new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build());</syntaxhighlight>
Follow the link for extra details about the 'NutritionFacts' class example.
Follow the link for extra details about the 'NutritionFacts' class example.


=={{header|JavaScript}}==
=={{header|JavaScript}}==
JavaScript only has positional parameters, but named parameters can be emulated by passing an object with the appropriate properties:
JavaScript only has positional parameters, but named parameters can be emulated by passing an object with the appropriate properties:
<lang javascript>function example(options) {
<syntaxhighlight lang="javascript">function example(options) {
// assign some defaults where the user's has not provided a value
// assign some defaults where the user's has not provided a value
opts = {}
opts = {}
Line 852: Line 852:


example({grill: "lamb kebab", bar: 3.14});
example({grill: "lamb kebab", bar: 3.14});
// => "foo is 0, bar is 3.14, and grill is lamb kebab"</lang>
// => "foo is 0, bar is 3.14, and grill is lamb kebab"</syntaxhighlight>
===ECMAScript 2015 (ES6) variants===
===ECMAScript 2015 (ES6) variants===
With this version, ECMAScript adds destrucuring assignments and destructuring in function parameters. Thus you could do something like this (this works in ES6 Fiddle, but is syntax error in Mozilla SpiderMonkey JS Shell, so uses console.log instead of print):<lang javascript>let
With this version, ECMAScript adds destrucuring assignments and destructuring in function parameters. Thus you could do something like this (this works in ES6 Fiddle, but is syntax error in Mozilla SpiderMonkey JS Shell, so uses console.log instead of print):<syntaxhighlight lang="javascript">let
example = // The member name in the object can either be the same as the parameter (as in bar, grill),
example = // The member name in the object can either be the same as the parameter (as in bar, grill),
// or a different parameter name as in the case of member foo being assigned to parameter a here.
// or a different parameter name as in the case of member foo being assigned to parameter a here.
Line 865: Line 865:
// foo is 0 , bar is 3.14 , and grill is lamb kebab
// foo is 0 , bar is 3.14 , and grill is lamb kebab
example({foo:null});
example({foo:null});
// foo is , bar is 1 , and grill is pork chops</lang>
// foo is , bar is 1 , and grill is pork chops</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
Line 871: Line 871:


For example, here is the jq analog of "print-name" defined in the Common Lisp section above. Here we format the full name and return it as a string:
For example, here is the jq analog of "print-name" defined in the Common Lisp section above. Here we format the full name and return it as a string:
<syntaxhighlight lang="jq">
<lang jq>
def formatName(obj):
def formatName(obj):
({ "name": "?"} + obj) as $obj # the default default value is null
({ "name": "?"} + obj) as $obj # the default default value is null
Line 879: Line 879:
else $name + ", " + $first
else $name + ", " + $first
end;
end;
</syntaxhighlight>
</lang>


Here are examples of how the function can be invoked:
Here are examples of how the function can be invoked:
<syntaxhighlight lang="jq">
<lang jq>
formatName({"first": "George", "name": "Eliot"})
formatName({"first": "George", "name": "Eliot"})


Line 892: Line 892:


formatName({})
formatName({})
</syntaxhighlight>
</lang>


=={{header|Julia}}==
=={{header|Julia}}==
Julia supports arbitrary named keyword arguments, which are listed (with their default values) after a <code>;</code> in the function definition:
Julia supports arbitrary named keyword arguments, which are listed (with their default values) after a <code>;</code> in the function definition:
<lang Julia>function surround(string ; border = :default, padding = 0)
<syntaxhighlight lang="julia">function surround(string ; border = :default, padding = 0)


ve, ho, ul, ur, dl, dr =
ve, ho, ul, ur, dl, dr =
Line 909: Line 909:
ve, " "^padding, string," "^padding, ve, "\n",
ve, " "^padding, string," "^padding, ve, "\n",
dl, ho^(length(string) + 2padding), dr)
dl, ho^(length(string) + 2padding), dr)
end</lang>
end</syntaxhighlight>


{{Out}}
{{Out}}
Line 923: Line 923:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun someFunction(first: String, second: Int = 2, third: Double) {
fun someFunction(first: String, second: Int = 2, third: Double) {
Line 941: Line 941:
// using first and third parameters in reverse
// using first and third parameters in reverse
someFunction(third = 2.0, first = "reversed")
someFunction(third = 2.0, first = "reversed")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 960: Line 960:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>define mymethod(
<syntaxhighlight lang="lasso">define mymethod(
-first::integer, // with no default value the param is required
-first::integer, // with no default value the param is required
-second::integer,
-second::integer,
Line 975: Line 975:
-first = 54,
-first = 54,
-delimiter = '#'
-delimiter = '#'
)</lang>
)</syntaxhighlight>
-> 54:45
-> 54:45


Line 982: Line 982:
=={{header|Lingo}}==
=={{header|Lingo}}==
Lingo does not support named function parameters. But this can be simulated by using a single property list (hash) with named properties as function argument. You can also create functions that support both calling methods, like e.g. this function that accepts either 3 integers or a single property list with such named properties:
Lingo does not support named function parameters. But this can be simulated by using a single property list (hash) with named properties as function argument. You can also create functions that support both calling methods, like e.g. this function that accepts either 3 integers or a single property list with such named properties:
<lang lingo>-- accepts either 3 integers or a single property list
<syntaxhighlight lang="lingo">-- accepts either 3 integers or a single property list
on foo (arg1, arg2, arg3)
on foo (arg1, arg2, arg3)
if ilk(arg1)=#propList then
if ilk(arg1)=#propList then
Line 1,003: Line 1,003:
-- "arg1="
-- "arg1="
-- "arg2="
-- "arg2="
-- "arg3=3"</lang>
-- "arg3=3"</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<syntaxhighlight lang="lua">
<lang Lua>
function CreatePet(options)
function CreatePet(options)
local name=options.name
local name=options.name
Line 1,015: Line 1,015:
CreatePet{name='Rex',species='Dog',breed='Irish Setter'}
CreatePet{name='Rex',species='Dog',breed='Irish Setter'}
--position does not matter here.
--position does not matter here.
</syntaxhighlight>
</lang>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Line 1,021: Line 1,021:
Passing optionals in modules may cause problems if we have values in stack, so we can use Stack New {] to open an empty current stack (the old one is hidden until exit from that block), or using ? as "use standard value".
Passing optionals in modules may cause problems if we have values in stack, so we can use Stack New {] to open an empty current stack (the old one is hidden until exit from that block), or using ? as "use standard value".


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
module namedparam (x as decimal=10, y as integer=50) {
module namedparam (x as decimal=10, y as integer=50) {
Print type$(x), x
Print type$(x), x
Line 1,036: Line 1,036:
}
}
namedparam %x=1, %y=1
namedparam %x=1, %y=1
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<lang maple>f := proc(a, {b:= 1, c:= 1})
<syntaxhighlight lang="maple">f := proc(a, {b:= 1, c:= 1})
print (a*(c+b));
print (a*(c+b));
end proc:
end proc:
Line 1,048: Line 1,048:
3
3
f(2, b = 5, c = 3);#b and c can be put in any order
f(2, b = 5, c = 3);#b and c can be put in any order
16</lang>
16</syntaxhighlight>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Options[fn]={Add->False,Offset-> 0};
<syntaxhighlight lang="mathematica">Options[fn]={Add->False,Offset-> 0};
fn[x_,y_,OptionsPattern[]]:=If[OptionValue[Add]==True,x+y+OptionValue[Offset],{x,y,OptionValue[Offset]}]
fn[x_,y_,OptionsPattern[]]:=If[OptionValue[Add]==True,x+y+OptionValue[Offset],{x,y,OptionValue[Offset]}]
fn[3,4,{Add->True,Offset->2}]
fn[3,4,{Add->True,Offset->2}]
fn[3,4,{Offset->2,Add->True}]</lang>
fn[3,4,{Offset->2,Add->True}]</syntaxhighlight>
{{out}}
{{out}}
<pre>9
<pre>9
Line 1,063: Line 1,063:
Named parameters are not natively supported. However, the following code can be used to implement them.
Named parameters are not natively supported. However, the following code can be used to implement them.


<lang Matlab> function foo(varargin)
<syntaxhighlight lang="matlab"> function foo(varargin)
for k= 1:2:length(varargin);
for k= 1:2:length(varargin);
switch (varargin{k})
switch (varargin{k})
Line 1,077: Line 1,077:


foo('param1','a1','param2','b2');
foo('param1','a1','param2','b2');
foo('param2','b2','param1','a1'); </lang>
foo('param2','b2','param1','a1'); </syntaxhighlight>


Output:
Output:
Line 1,090: Line 1,090:
Much like [[Ada]], Modula-3 allows either positional or keyed association of actual parameters. Defaults can also be ignored.
Much like [[Ada]], Modula-3 allows either positional or keyed association of actual parameters. Defaults can also be ignored.


<lang modula3>PROCEDURE Foo(Arg1: INTEGER; Arg2: REAL := 0.0);</lang>
<syntaxhighlight lang="modula3">PROCEDURE Foo(Arg1: INTEGER; Arg2: REAL := 0.0);</syntaxhighlight>
It can be equivalently called as:
It can be equivalently called as:
<lang modula3>Foo(1, 0.0);
<syntaxhighlight lang="modula3">Foo(1, 0.0);
Foo(1);
Foo(1);
Foo(Arg2 := 0.0, Arg1 := 1);
Foo(Arg2 := 0.0, Arg1 := 1);
Foo(Arg1 := 1);</lang>
Foo(Arg1 := 1);</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>Foo(number : int, word = "Default", option = true) : void // note type inference with default values
<syntaxhighlight lang="nemerle">Foo(number : int, word = "Default", option = true) : void // note type inference with default values


Foo(word = "Bird", number = 3) // an argument with a default value can be omitted from function call
Foo(word = "Bird", number = 3) // an argument with a default value can be omitted from function call
Foo(3, option = false, word = "Bird") // unnamed arguments must be in same order as function definition and precede named arguments
Foo(3, option = false, word = "Bird") // unnamed arguments must be in same order as function definition and precede named arguments
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
In Nim, a regular parameter of a procedure can be used as either a positional or a named parameter.
In Nim, a regular parameter of a procedure can be used as either a positional or a named parameter.


<lang nim>proc subtract(x, y): auto = x - y
<syntaxhighlight lang="nim">proc subtract(x, y): auto = x - y


echo subtract(5, 3) # used as positional parameters
echo subtract(5, 3) # used as positional parameters
echo subtract(y = 3, x = 5) # used as named parameters</lang>
echo subtract(y = 3, x = 5) # used as named parameters</syntaxhighlight>


Parameters can be made optional by providing a default argument.
Parameters can be made optional by providing a default argument.
Line 1,116: Line 1,116:
=={{header|Objective-C}}==
=={{header|Objective-C}}==
Objective-C, like Smalltalk, has a method call syntax that is visually identical to named arguments, but they are not optional and may not be reordered. (Optional arguments may be simulated by defining multiple methods with the same leading name part.)
Objective-C, like Smalltalk, has a method call syntax that is visually identical to named arguments, but they are not optional and may not be reordered. (Optional arguments may be simulated by defining multiple methods with the same leading name part.)
<lang objc>@interface Demo : NSObject {
<syntaxhighlight lang="objc">@interface Demo : NSObject {
// Omitted ...
// Omitted ...
}
}
Line 1,123: Line 1,123:
- (double) hypotenuseOfX: (double)x andY: (double)y andZ: (double)z;
- (double) hypotenuseOfX: (double)x andY: (double)y andZ: (double)z;


@end</lang>
@end</syntaxhighlight>
<lang objc>@implementation Demo
<syntaxhighlight lang="objc">@implementation Demo


- (double) hypotenuseOfX: (double)x andY: (double)y {
- (double) hypotenuseOfX: (double)x andY: (double)y {
Line 1,133: Line 1,133:
}
}


@end</lang>
@end</syntaxhighlight>
<lang objc>Demo *example = [[Demo alloc] init];
<syntaxhighlight lang="objc">Demo *example = [[Demo alloc] init];
double h = [example hypotenuseOfX:1.23 andY:3.79];</lang>
double h = [example hypotenuseOfX:1.23 andY:3.79];</syntaxhighlight>
Note in the example above that the name of the method, the ''selector''; is actually “<code>hypotenuseOfX:andY:</code>”.
Note in the example above that the name of the method, the ''selector''; is actually “<code>hypotenuseOfX:andY:</code>”.


=={{header|OCaml}}==
=={{header|OCaml}}==
You can make a named argument (called ''labels'' in OCaml) by putting a tilde (~) before the name:
You can make a named argument (called ''labels'' in OCaml) by putting a tilde (~) before the name:
<lang ocaml># let foo ~arg1 ~arg2 = arg1 + arg2;;
<syntaxhighlight lang="ocaml"># let foo ~arg1 ~arg2 = arg1 + arg2;;
val foo : arg1:int -> arg2:int -> int = <fun>
val foo : arg1:int -> arg2:int -> int = <fun>


Line 1,147: Line 1,147:


# foo ~arg2:17 ~arg1:42;;
# foo ~arg2:17 ~arg1:42;;
- : int = 59</lang>
- : int = 59</syntaxhighlight>


Named arguments can be re-ordered, but two arguments of the same label cannot be re-ordered relative to each other.
Named arguments can be re-ordered, but two arguments of the same label cannot be re-ordered relative to each other.
Line 1,157: Line 1,157:
=={{header|Oz}}==
=={{header|Oz}}==
For <b>methods</b>, Oz does support named parameters with default values. The named parameters can be freely reordered.
For <b>methods</b>, Oz does support named parameters with default values. The named parameters can be freely reordered.
<lang oz>declare
<syntaxhighlight lang="oz">declare
class Foo
class Foo
meth init skip end
meth init skip end
Line 1,171: Line 1,171:
{O bar(1 named1:2 named2:3 namedWithDefault:4)} %% ok
{O bar(1 named1:2 named2:3 namedWithDefault:4)} %% ok
{O bar(1 named2:2 named1:3)} %% ok
{O bar(1 named2:2 named1:3)} %% ok
{O bar(1 named1:2)} %% not ok, "missing message feature in object application"</lang>
{O bar(1 named1:2)} %% not ok, "missing message feature in object application"</syntaxhighlight>


For <b>procedures</b> only positional parameters are supported. However, you can emulate named parameters by using records:
For <b>procedures</b> only positional parameters are supported. However, you can emulate named parameters by using records:
<syntaxhighlight lang="oz">
<lang oz>
declare
declare
proc {Foo PP Other=unit(named1:N1 named2:N2 ...)}
proc {Foo PP Other=unit(named1:N1 named2:N2 ...)}
Line 1,184: Line 1,184:
{Foo 1 unit(named1:2 named2:3 namedWithDefault:4)}
{Foo 1 unit(named1:2 named2:3 namedWithDefault:4)}
{Foo 1 unit(named2:2 named1:3)}
{Foo 1 unit(named2:2 named1:3)}
{Foo 1 unit(named1:2)} %% not ok...</lang>
{Foo 1 unit(named1:2)} %% not ok...</syntaxhighlight>


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").
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").
Line 1,193: Line 1,193:
Perl has no non-experimental formal parameters. Instead, Perl subroutines access all of their arguments through the special array <code>@_</code>. You can easily implement named arguments by making your function interpret <code>@_</code> (or part of it) as a hash.
Perl has no non-experimental formal parameters. Instead, Perl subroutines access all of their arguments through the special array <code>@_</code>. You can easily implement named arguments by making your function interpret <code>@_</code> (or part of it) as a hash.


<lang perl>sub funkshun {
<syntaxhighlight lang="perl">sub funkshun {
my %h = @_;
my %h = @_;
# Print every argument and its value.
# Print every argument and its value.
Line 1,204: Line 1,204:
# Otherwise, say that it's off.
# Otherwise, say that it's off.
print "Safe mode ", ($h{safe} ? 'on' : 'off'), ".\n";
print "Safe mode ", ($h{safe} ? 'on' : 'off'), ".\n";
}</lang>
}</syntaxhighlight>
The semantics of calling such a function follow directly from the semantics of using a hash. For instance, if you provide multiple values for the same named argument, only the last one will be used. An example call:
The semantics of calling such a function follow directly from the semantics of using a hash. For instance, if you provide multiple values for the same named argument, only the last one will be used. An example call:


<lang perl>funkshun(
<syntaxhighlight lang="perl">funkshun(
verbosity => 3,
verbosity => 3,
password => 'foobie blech',
password => 'foobie blech',
Line 1,213: Line 1,213:
'42' => 'answer',
'42' => 'answer',
password => 'joshua'
password => 'joshua'
);</lang>
);</syntaxhighlight>
Its output:
Its output:


Line 1,223: Line 1,223:
Safe mode off.</pre>
Safe mode off.</pre>


Further flexibility can be obtained by using [[Pass by reference]] semantics:<lang Perl>sub event
Further flexibility can be obtained by using [[Pass by reference]] semantics:<syntaxhighlight lang="perl">sub event
{
{
my ($params_ref, $name) = @_;
my ($params_ref, $name) = @_;
Line 1,259: Line 1,259:
},
},
"Joe Schmoe"
"Joe Schmoe"
);</lang>Prints:
);</syntaxhighlight>Prints:
<pre>
<pre>
Joe Schmoe called event() with the following named parameters:
Joe Schmoe called event() with the following named parameters:
Line 1,281: Line 1,281:


The classic example (inspired by the standard Python equivalent) is that builtins\timedate.e defines:
The classic example (inspired by the standard Python equivalent) is that builtins\timedate.e defines:
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #000000;">timedelta</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">weeks</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">days</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hours</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">minutes</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">seconds</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">milliseconds</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">microseconds</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #000000;">timedelta</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">weeks</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">days</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hours</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">minutes</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">seconds</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">milliseconds</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">microseconds</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


which can be invoked as follows:
which can be invoked as follows:


<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">timedate</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">timedate</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 1,308: Line 1,308:


<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"shift = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">shift</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"shift = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">shift</span><span style="color: #0000FF;">)})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
Note that pwa/p2js automatically maps named parameters to positional parameters for you, since JavaScript does not support named parameters.
Note that pwa/p2js automatically maps named parameters to positional parameters for you, since JavaScript does not support named parameters.
{{out}}
{{out}}
Line 1,319: Line 1,319:
=={{header|PHP}}==
=={{header|PHP}}==
PHP doesn't support named parameters but you can simulate the behavior with PHP arrays.
PHP doesn't support named parameters but you can simulate the behavior with PHP arrays.
<lang PHP>function named($args) {
<syntaxhighlight lang="php">function named($args) {
$args += ["gbv" => 2,
$args += ["gbv" => 2,
"motor" => "away",
"motor" => "away",
Line 1,326: Line 1,326:
}
}


named(["teenage" => "cia", "gbv" => 10]);</lang>
named(["teenage" => "cia", "gbv" => 10]);</syntaxhighlight>
Output:
Output:
<pre>10 men running away from the cia</pre>
<pre>10 men running away from the cia</pre>
Line 1,335: Line 1,335:
to establish bindings to passed names.
to establish bindings to passed names.
===Passing symbol-value pairs===
===Passing symbol-value pairs===
<lang PicoLisp>(de foo @
<syntaxhighlight lang="picolisp">(de foo @
(bind (rest) # Bind symbols in CARs to values in CDRs
(bind (rest) # Bind symbols in CARs to values in CDRs
(println 'Bar 'is Bar)
(println 'Bar 'is Bar)
(println 'Mumble 'is Mumble) ) )
(println 'Mumble 'is Mumble) ) )


(foo '(Bar . 123) '(Mumble . "def"))</lang>
(foo '(Bar . 123) '(Mumble . "def"))</syntaxhighlight>
===Passing a name list followed by values===
===Passing a name list followed by values===
<lang PicoLisp>(de foo @
<syntaxhighlight lang="picolisp">(de foo @
(bind (next) # Save all symbols in first argument
(bind (next) # Save all symbols in first argument
(mapc set (arg) (rest)) # then bind them to remaining arguments
(mapc set (arg) (rest)) # then bind them to remaining arguments
Line 1,348: Line 1,348:
(println 'Mumble 'is Mumble) ) )
(println 'Mumble 'is Mumble) ) )


(foo '(Bar Mumble) 123 "def")</lang>
(foo '(Bar Mumble) 123 "def")</syntaxhighlight>
Output in both cases:
Output in both cases:
<pre>Bar is 123
<pre>Bar is 123
Line 1,356: Line 1,356:
===Positional parameters===
===Positional parameters===
When writing a function and not stating any parameters explicitly, such as the following function
When writing a function and not stating any parameters explicitly, such as the following function
<lang powershell>function Test {
<syntaxhighlight lang="powershell">function Test {
Write-Host Argument 1 is $args[0]
Write-Host Argument 1 is $args[0]
}</lang>
}</syntaxhighlight>
the only option are positional parameters using the <code>$args</code> array.
the only option are positional parameters using the <code>$args</code> array.
===Named parameters===
===Named parameters===
Stating any number of parameters directly in the function definition, such as
Stating any number of parameters directly in the function definition, such as
<lang powershell>function Test ($SomeArgument, $AnotherArgument, $ThirdArgument) {
<syntaxhighlight lang="powershell">function Test ($SomeArgument, $AnotherArgument, $ThirdArgument) {
Write-Host "Some argument: $SomeArgument"
Write-Host "Some argument: $SomeArgument"
Write-Host "Another argument: $AnotherArgument"
Write-Host "Another argument: $AnotherArgument"
Write-Host "Third argument: $ThirdArgument"
Write-Host "Third argument: $ThirdArgument"
}</lang>
}</syntaxhighlight>
will cause them to be named automatically which enables the caller to state the arguments in any order. The syntax follows the convention used with cmdlets as well:
will cause them to be named automatically which enables the caller to state the arguments in any order. The syntax follows the convention used with cmdlets as well:
<pre>PS> Test -ThirdArgument foo -AnotherArgument bar -SomeArgument baz
<pre>PS> Test -ThirdArgument foo -AnotherArgument bar -SomeArgument baz
Line 1,382: Line 1,382:
===Switch parameters===
===Switch parameters===
Functions can have so-called ''switch parameters'' which are always boolean and either present or not. There is no need to give a value for them.
Functions can have so-called ''switch parameters'' which are always boolean and either present or not. There is no need to give a value for them.
<lang powershell>function SwitchTest ([switch] $on) {
<syntaxhighlight lang="powershell">function SwitchTest ([switch] $on) {
Write-Host Switched $(if ($on) { "on" } else { "off" })
Write-Host Switched $(if ($on) { "on" } else { "off" })
}</lang>
}</syntaxhighlight>
When calling a function with such a parameter the switch is simply given directly (which sets its value to ''true'') or omitted (which causes it to evaluate to ''false''):
When calling a function with such a parameter the switch is simply given directly (which sets its value to ''true'') or omitted (which causes it to evaluate to ''false''):
<pre>PS> SwitchTest
<pre>PS> SwitchTest
Line 1,392: Line 1,392:
===Optional parameters and default values===
===Optional parameters and default values===
Usually all parameters can be omitted. In the case of switch parameters this will cause them to assume the value ''false'', for normal parameters they will have the value <code>$null</code>. This is not always the desired value, though. Default values can be given too:
Usually all parameters can be omitted. In the case of switch parameters this will cause them to assume the value ''false'', for normal parameters they will have the value <code>$null</code>. This is not always the desired value, though. Default values can be given too:
<lang powershell>function Greeting ($Name = "Nobody") {
<syntaxhighlight lang="powershell">function Greeting ($Name = "Nobody") {
Write-Host Hello, $Name!
Write-Host Hello, $Name!
}</lang>
}</syntaxhighlight>
If the <code>Name</code> argument is omitted now, its value will be <code>"Nobody"</code> instead of <code>$null</code>:
If the <code>Name</code> argument is omitted now, its value will be <code>"Nobody"</code> instead of <code>$null</code>:
<pre>PS> Greeting
<pre>PS> Greeting
Line 1,403: Line 1,403:
=={{header|Prolog}}==
=={{header|Prolog}}==
{{works with|SWI Prolog}}
{{works with|SWI Prolog}}
<lang prolog>:- initialization(main).
<syntaxhighlight lang="prolog">:- initialization(main).


main :-
main :-
Line 1,417: Line 1,417:
member(A,C),
member(A,C),
named_args(B,C).
named_args(B,C).
</syntaxhighlight>
</lang>


=={{header|Python}}==
=={{header|Python}}==
Line 1,425: Line 1,425:
In Python, a regular parameter of a function can be used as ''either a positional or a named'' parameter. The variable name that you use for the parameter when you declare the function becomes the "name" for the parameter, should you use it as a named parameter. When you call a function, you use the "name = value" syntax to provide the argument to a named parameter. The named arguments must come after all the positional arguments.
In Python, a regular parameter of a function can be used as ''either a positional or a named'' parameter. The variable name that you use for the parameter when you declare the function becomes the "name" for the parameter, should you use it as a named parameter. When you call a function, you use the "name = value" syntax to provide the argument to a named parameter. The named arguments must come after all the positional arguments.


<lang python>def subtract(x, y):
<syntaxhighlight lang="python">def subtract(x, y):
return x - y
return x - y


subtract(5, 3) # used as positional parameters; evaluates to 2
subtract(5, 3) # used as positional parameters; evaluates to 2
subtract(y = 3, x = 5) # used as named parameters; evaluates to 2</lang>
subtract(y = 3, x = 5) # used as named parameters; evaluates to 2</syntaxhighlight>


Parameters can be made optional by providing a default argument, as described in the [[optional parameters]] article.
Parameters can be made optional by providing a default argument, as described in the [[optional parameters]] article.
Line 1,486: Line 1,486:


====Examples====
====Examples====
<lang python>>>> from __future__ import print_function
<syntaxhighlight lang="python">>>> from __future__ import print_function
>>>
>>>
>>> def show_args(defparam1, defparam2 = 'default value', *posparam, **keyparam):
>>> def show_args(defparam1, defparam2 = 'default value', *posparam, **keyparam):
Line 1,592: Line 1,592:
'EXTRA', 'POSITIONAL', 'ARGUMENTS')
'EXTRA', 'POSITIONAL', 'ARGUMENTS')
SyntaxError: non-keyword arg after keyword arg
SyntaxError: non-keyword arg after keyword arg
>>></lang>
>>></syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
Line 1,598: Line 1,598:
R parameters are all named; arguments can be passed either positionally or with explicit naming. The named arguments are matched to their parameters first, then the unnamed arguments fill in remaining slots. A parameter whose name begins with a period will not be matched to unnamed arguments. R allows abbreviated names to be used as long as they match uniquely to an argument.
R parameters are all named; arguments can be passed either positionally or with explicit naming. The named arguments are matched to their parameters first, then the unnamed arguments fill in remaining slots. A parameter whose name begins with a period will not be matched to unnamed arguments. R allows abbreviated names to be used as long as they match uniquely to an argument.


<lang rsplus>divide <- function(numerator, denominator) {
<syntaxhighlight lang="rsplus">divide <- function(numerator, denominator) {
numerator / denominator
numerator / denominator
}
}
Line 1,607: Line 1,607:
divide(den=3, num=2) # 0.66
divide(den=3, num=2) # 0.66
divide(den=3, 2) # 0.66
divide(den=3, 2) # 0.66
divide(3, num=2) # 0.66</lang>
divide(3, num=2) # 0.66</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Line 1,613: Line 1,613:
Racket has built-in keyword and optional arguments:
Racket has built-in keyword and optional arguments:


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 1,626: Line 1,626:
(pizza "tomato" #:topping "onion")
(pizza "tomato" #:topping "onion")
(pizza #:topping "onion" "garlic" #:type "pan")
(pizza #:topping "onion" "garlic" #:type "pan")
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 1,634: Line 1,634:
Raku's support for optional parameters is much like Python's. Consider this declaration:
Raku's support for optional parameters is much like Python's. Consider this declaration:


<lang perl6>sub funkshun ($a, $b?, $c = 15, :$d, *@e, *%f) {
<syntaxhighlight lang="raku" line>sub funkshun ($a, $b?, $c = 15, :$d, *@e, *%f) {
...
...
}</lang>
}</syntaxhighlight>


In the above signature:
In the above signature:
Line 1,648: Line 1,648:
So, if we defined the function like this:
So, if we defined the function like this:


<lang perl6>sub funkshun ($a, $b?, :$c = 15, :$d, *@e, *%f) {
<syntaxhighlight lang="raku" line>sub funkshun ($a, $b?, :$c = 15, :$d, *@e, *%f) {
say "$a $b $c $d";
say "$a $b $c $d";
say join ' ', @e;
say join ' ', @e;
Line 1,658: Line 1,658:
funkshun
funkshun
'Alfa', k1 => 'v1', c => 'Charlie', 'Bravo', 'e1',
'Alfa', k1 => 'v1', c => 'Charlie', 'Bravo', 'e1',
d => 'Delta', 'e2', k2 => 'v2';</lang>
d => 'Delta', 'e2', k2 => 'v2';</syntaxhighlight>


would print this:
would print this:
Line 1,668: Line 1,668:
=={{header|REXX}}==
=={{header|REXX}}==
===version 1===
===version 1===
<lang rexx>/*REXX pgm shows named parameters when called as a subroutine/function*/
<syntaxhighlight lang="rexx">/*REXX pgm shows named parameters when called as a subroutine/function*/
/*┌────────────────────────────────────────────────────────────────────┐
/*┌────────────────────────────────────────────────────────────────────┐
│ The syntax of: xxx = func1(parmName2=arg2, parmName1=arg1) │
│ The syntax of: xxx = func1(parmName2=arg2, parmName1=arg1) │
Line 1,743: Line 1,743:


return 'the final meaning of life, or 42 --- whichever is appropriate.'
return 'the final meaning of life, or 42 --- whichever is appropriate.'
/*stick a fork in it, we're done.*/</lang>
/*stick a fork in it, we're done.*/</syntaxhighlight>
===version 2===
===version 2===
<lang rexx>/* REXX ---------------------------------------------------------------
<syntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 01.07.2014 Walter Pachl
* 01.07.2014 Walter Pachl
* Argument values must not start with 'arg'
* Argument values must not start with 'arg'
Line 1,765: Line 1,765:
Say 'p.'i'='p.i
Say 'p.'i'='p.i
End
End
Return p.1**p.2</lang>
Return p.1**p.2</syntaxhighlight>
{{Out}}
{{Out}}
<pre>p.1=2
<pre>p.1=2
Line 1,780: Line 1,780:
{{trans|Tcl}}
{{trans|Tcl}}
{{works with|Ruby|2.0}}
{{works with|Ruby|2.0}}
<lang ruby>def example(foo: 0, bar: 1, grill: "pork chops")
<syntaxhighlight lang="ruby">def example(foo: 0, bar: 1, grill: "pork chops")
puts "foo is #{foo}, bar is #{bar}, and grill is #{grill}"
puts "foo is #{foo}, bar is #{bar}, and grill is #{grill}"
end
end


# Note that :foo is omitted and :grill precedes :bar
# Note that :foo is omitted and :grill precedes :bar
example(grill: "lamb kebab", bar: 3.14)</lang>
example(grill: "lamb kebab", bar: 3.14)</syntaxhighlight>


Ruby 1.9 can fake the effect with a Hash. If a caller passes <code>name: value</code> pairs, Ruby makes a Hash, and the called method sees this Hash in its last argument. To complete the effect, the method may declare an optional last argument that defaults to an empty Hash <code>{}</code>. In this version, <code>example(typo: 4)</code> causes no error.
Ruby 1.9 can fake the effect with a Hash. If a caller passes <code>name: value</code> pairs, Ruby makes a Hash, and the called method sees this Hash in its last argument. To complete the effect, the method may declare an optional last argument that defaults to an empty Hash <code>{}</code>. In this version, <code>example(typo: 4)</code> causes no error.
Line 1,791: Line 1,791:
{{works with|Ruby|1.9}}
{{works with|Ruby|1.9}}


<lang ruby>def example(opts = {})
<syntaxhighlight lang="ruby">def example(opts = {})
# Hash#merge raises TypeError if _opts_ is not a Hash.
# Hash#merge raises TypeError if _opts_ is not a Hash.
# Nothing checks if _opts_ contains unknown keys.
# Nothing checks if _opts_ contains unknown keys.
Line 1,801: Line 1,801:
end
end


example(grill: "lamb kebab", bar: 3.14)</lang>
example(grill: "lamb kebab", bar: 3.14)</syntaxhighlight>


Ruby 1.8 and older versions can do the same, but must use the old syntax <code>:name => value</code>.
Ruby 1.8 and older versions can do the same, but must use the old syntax <code>:name => value</code>.


<lang ruby>def example(opts = {})
<syntaxhighlight lang="ruby">def example(opts = {})
defaults = {:foo => 0, :bar => 1, :grill => "pork chops"}
defaults = {:foo => 0, :bar => 1, :grill => "pork chops"}
opts = defaults.merge(opts)
opts = defaults.merge(opts)
Line 1,812: Line 1,812:
end
end


example(:grill => "lamb kebab", :bar => 3.14)</lang>
example(:grill => "lamb kebab", :bar => 3.14)</syntaxhighlight>


{{omit from|Rust}}
{{omit from|Rust}}
Line 1,820: Line 1,820:
Scala 2.8 utilizes named parameters and default values:
Scala 2.8 utilizes named parameters and default values:


<lang scala>
<syntaxhighlight lang="scala">
def add(x: Int, y: Int = 1) = x + y
def add(x: Int, y: Int = 1) = x + y
</syntaxhighlight>
</lang>


<lang scala>
<syntaxhighlight lang="scala">
scala> add(5)
scala> add(5)
6
6
Line 1,830: Line 1,830:
scala> add(y=10, x=4)
scala> add(y=10, x=4)
14
14
</syntaxhighlight>
</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(define (keyarg-parser argdefs args kont)
(define (keyarg-parser argdefs args kont)
(apply kont
(apply kont
Line 1,855: Line 1,855:
(display first)))
(display first)))
(newline))))
(newline))))
</syntaxhighlight>
</lang>


<lang scheme>
<syntaxhighlight lang="scheme">
=> (print-name)
=> (print-name)
?
?
Line 1,866: Line 1,866:
=>(print-name 'last "Doe")
=>(print-name 'last "Doe")
Doe
Doe
</syntaxhighlight>
</lang>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
The <b>introduce</b> handler here includes a default value for <b>greeting</b>. Ordinarily, parameters are passed sequentially, but <code>by name</code> can be used to match values from a property list to the corresponding parameters of the handler that is being called.<lang sensetalk>introduce "Mary"
The <b>introduce</b> handler here includes a default value for <b>greeting</b>. Ordinarily, parameters are passed sequentially, but <code>by name</code> can be used to match values from a property list to the corresponding parameters of the handler that is being called.<syntaxhighlight lang="sensetalk">introduce "Mary"
introduce "Pablo", "Hola"
introduce "Pablo", "Hola"
introduce greeting:"Bonjour", name:"Brigitte" by name
introduce greeting:"Bonjour", name:"Brigitte" by name
Line 1,876: Line 1,876:
put greeting && name
put greeting && name
end introduce
end introduce
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,885: Line 1,885:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func example(foo: 0, bar: 1, grill: "pork chops") {
<syntaxhighlight lang="ruby">func example(foo: 0, bar: 1, grill: "pork chops") {
say "foo is #{foo}, bar is #{bar}, and grill is #{grill}";
say "foo is #{foo}, bar is #{bar}, and grill is #{grill}";
}
}


# Note that :foo is omitted and :grill precedes :bar
# Note that :foo is omitted and :grill precedes :bar
example(grill: "lamb kebab", bar: 3.14);</lang>
example(grill: "lamb kebab", bar: 3.14);</syntaxhighlight>
{{out}}
{{out}}
<pre>foo is 0, bar is 3.14, and grill is lamb kebab</pre>
<pre>foo is 0, bar is 3.14, and grill is lamb kebab</pre>
Line 1,900: Line 1,900:
{{works with|GNU Smalltalk}}
{{works with|GNU Smalltalk}}


<lang smalltalk>Object subclass: AnotherClass [
<syntaxhighlight lang="smalltalk">Object subclass: AnotherClass [
"..."
"..."
initWithArray: anArray [ "single argument" ]
initWithArray: anArray [ "single argument" ]
Line 1,908: Line 1,908:
]
]
"..."
"..."
]</lang>
]</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
This example uses Standard ML "fields".
This example uses Standard ML "fields".
<lang sml>fun dosomething (a, b, c) = print ("a = " ^ a ^ "\nb = " ^ Real.toString b ^ "\nc = " ^ Int.toString c ^ "\n")
<syntaxhighlight lang="sml">fun dosomething (a, b, c) = print ("a = " ^ a ^ "\nb = " ^ Real.toString b ^ "\nc = " ^ Int.toString c ^ "\n")


fun example {a, b, c} = dosomething (a, b, c)</lang>
fun example {a, b, c} = dosomething (a, b, c)</syntaxhighlight>


To call the procedure ''example'', use:
To call the procedure ''example'', use:
<lang sml>example {a="Hello World!", b=3.14, c=42}</lang>
<syntaxhighlight lang="sml">example {a="Hello World!", b=3.14, c=42}</syntaxhighlight>
However, this does not support optional parameters. To emulate them, we can process a parameter list:
However, this does not support optional parameters. To emulate them, we can process a parameter list:
<lang sml>datatype param = A of string | B of real | C of int
<syntaxhighlight lang="sml">datatype param = A of string | B of real | C of int


fun args xs =
fun args xs =
Line 1,930: Line 1,930:
map (fn (A x) => a := x | (B x) => b := x | (C x) => c := x) xs;
map (fn (A x) => a := x | (B x) => b := x | (C x) => c := x) xs;
(!a, !b, !c)
(!a, !b, !c)
end</lang>
end</syntaxhighlight>
To process the argument list and call ''example'', use:
To process the argument list and call ''example'', use:
<lang sml>dosomething (args [A "tam", B 42.0]);</lang>
<syntaxhighlight lang="sml">dosomething (args [A "tam", B 42.0]);</syntaxhighlight>


=={{header|Suneido}}==
=={{header|Suneido}}==
Suneido can handle named and unnamed parameters. When using a combination, unnamed parameters must come before named ones and must be in the correct order. Named parameters can be in any order. Named parameters are given a default value so they are not mandatory.
Suneido can handle named and unnamed parameters. When using a combination, unnamed parameters must come before named ones and must be in the correct order. Named parameters can be in any order. Named parameters are given a default value so they are not mandatory.
<syntaxhighlight lang="suneido">
<lang Suneido>
test = function (one, two, three = '', four = '', five = '')
test = function (one, two, three = '', four = '', five = '')
{
{
Line 1,943: Line 1,943:
}
}
test('1', '2', five: '5', three: '3')
test('1', '2', five: '5', three: '3')
</syntaxhighlight>
</lang>
Output:
Output:
<lang Suneido>one: 1, two: 2, three: 3, four: , five: 5</lang>
<syntaxhighlight lang="suneido">one: 1, two: 2, three: 3, four: , five: 5</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
Each function parameter has both an argument label and a parameter name. The argument label is used when calling the function; each argument is written in the function call with its argument label before it. The parameter name is used in the implementation of the function. By default, parameters use their parameter name as their argument label.
Each function parameter has both an argument label and a parameter name. The argument label is used when calling the function; each argument is written in the function call with its argument label before it. The parameter name is used in the implementation of the function. By default, parameters use their parameter name as their argument label.


<lang Swift>func greet(person: String, hometown: String) -> String {
<syntaxhighlight lang="swift">func greet(person: String, hometown: String) -> String {
return "Hello \(person)! Glad you could visit from \(hometown)."
return "Hello \(person)! Glad you could visit from \(hometown)."
}
}
print(greet(person: "Bill", hometown: "Cupertino"))</lang>
print(greet(person: "Bill", hometown: "Cupertino"))</syntaxhighlight>
You write an argument label before the parameter name, separated by a space:
You write an argument label before the parameter name, separated by a space:
<lang Swift>func greet(person: String, from hometown: String) -> String {
<syntaxhighlight lang="swift">func greet(person: String, from hometown: String) -> String {
return "Hello \(person)! Glad you could visit from \(hometown)."
return "Hello \(person)! Glad you could visit from \(hometown)."
}
}
print(greet(person: "Bill", from: "Cupertino"))</lang>
print(greet(person: "Bill", from: "Cupertino"))</syntaxhighlight>


If you don’t want an argument label for a parameter, write an underscore (_) instead of an explicit argument label for that parameter.
If you don’t want an argument label for a parameter, write an underscore (_) instead of an explicit argument label for that parameter.
If a parameter has an argument label, the argument must be labeled when you call the function.
If a parameter has an argument label, the argument must be labeled when you call the function.
<lang Swift>func greet(_ person: String, _ hometown: String) -> String {
<syntaxhighlight lang="swift">func greet(_ person: String, _ hometown: String) -> String {
return "Hello \(person)! Glad you could visit from \(hometown)."
return "Hello \(person)! Glad you could visit from \(hometown)."
}
}
print(greet("Bill", "Cupertino"))</lang>
print(greet("Bill", "Cupertino"))</syntaxhighlight>


You can define a default value for any parameter in a function by assigning a value to the parameter after that parameter’s type. If a default value is defined, you can omit that parameter when calling the function.
You can define a default value for any parameter in a function by assigning a value to the parameter after that parameter’s type. If a default value is defined, you can omit that parameter when calling the function.
<lang Swift>func greet(person: String, from hometown: String = "Cupertino") -> String {
<syntaxhighlight lang="swift">func greet(person: String, from hometown: String = "Cupertino") -> String {
return "Hello \(person)! Glad you could visit from \(hometown)."
return "Hello \(person)! Glad you could visit from \(hometown)."
}
}
print(greet(person: "Bill"))</lang>
print(greet(person: "Bill"))</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
===Using arrays===
===Using arrays===
The simplest way of passing named parameters is to use the Tcl language's strong support for [[Varargs#Tcl|variadic commands]] together with its arrays. By convention (originally from [[Tk]]) the named parameters names start with a hyphen (“<tt>-</tt>”) and are called options.
The simplest way of passing named parameters is to use the Tcl language's strong support for [[Varargs#Tcl|variadic commands]] together with its arrays. By convention (originally from [[Tk]]) the named parameters names start with a hyphen (“<tt>-</tt>”) and are called options.
<lang tcl>proc example args {
<syntaxhighlight lang="tcl">proc example args {
# Set the defaults
# Set the defaults
array set opts {-foo 0 -bar 1 -grill "hamburger"}
array set opts {-foo 0 -bar 1 -grill "hamburger"}
Line 1,986: Line 1,986:
# Note that -foo is omitted and -grill precedes -bar
# Note that -foo is omitted and -grill precedes -bar
example -grill "lamb kebab" -bar 3.14
example -grill "lamb kebab" -bar 3.14
# => ‘foo is 0, bar is 3.14, and grill is lamb kebab’</lang>
# => ‘foo is 0, bar is 3.14, and grill is lamb kebab’</syntaxhighlight>
More complex option parsing is possible, e.g., with the <tt>opt</tt> package (of which only a small fraction of the functionality is shown here). This package also allows you to specify type constraints, though that is usually not necessary, and will generate a standard help message that can be obtained with the <tt>-help</tt> option:
More complex option parsing is possible, e.g., with the <tt>opt</tt> package (of which only a small fraction of the functionality is shown here). This package also allows you to specify type constraints, though that is usually not necessary, and will generate a standard help message that can be obtained with the <tt>-help</tt> option:
<lang tcl>package require opt
<syntaxhighlight lang="tcl">package require opt
tcl::OptProc example {
tcl::OptProc example {
{-foo -int 0 "The number of foos"}
{-foo -int 0 "The number of foos"}
Line 2,005: Line 2,005:
# -foo int (0) The number of foos
# -foo int (0) The number of foos
# -bar float (1.0) How much bar-ness
# -bar float (1.0) How much bar-ness
# -grill any (hamburger) What to cook on the grill</lang>
# -grill any (hamburger) What to cook on the grill</syntaxhighlight>


According to [http://wiki.tcl.tk/1730 wiki.tcl.tk discussions], '''::tcl::OptProc is deprecated.'''
According to [http://wiki.tcl.tk/1730 wiki.tcl.tk discussions], '''::tcl::OptProc is deprecated.'''
Line 2,012: Line 2,012:
===Using dicts===
===Using dicts===
Now (8.5) that dicts are here to replace arrays in most places, this can be achieved more cleanly as long as you do the authorized key checking yourself. Example of summary testing (to put in a nice uplevel wrapper):
Now (8.5) that dicts are here to replace arrays in most places, this can be achieved more cleanly as long as you do the authorized key checking yourself. Example of summary testing (to put in a nice uplevel wrapper):
<lang tcl>proc example {x y args} {
<syntaxhighlight lang="tcl">proc example {x y args} {
set keyargs {arg1 default1 arg2 default2}
set keyargs {arg1 default1 arg2 default2}
if {[llength $args] % 2 != 0} {
if {[llength $args] % 2 != 0} {
Line 2,027: Line 2,027:
example 1 2 arg2 3 # => x: 1, y: 2, arg1: default1, arg2: 3
example 1 2 arg2 3 # => x: 1, y: 2, arg1: default1, arg2: 3
example 1 2 test 3 # => test 3: invalid keyword arguments (spec: arg1 default1 arg2 default2)
example 1 2 test 3 # => test 3: invalid keyword arguments (spec: arg1 default1 arg2 default2)
example 1 2 test # => test: invalid keyword arguments (spec: arg1 default1 arg2 default2)</lang>
example 1 2 test # => test: invalid keyword arguments (spec: arg1 default1 arg2 default2)</syntaxhighlight>


Of course, more work is required to reach the flexibility of something like Common Lisp's ordinary lambda list.
Of course, more work is required to reach the flexibility of something like Common Lisp's ordinary lambda list.
Line 2,033: Line 2,033:


=={{header|VBA}}==
=={{header|VBA}}==
{{trans|Phix}}<lang vb>
{{trans|Phix}}<syntaxhighlight lang="vb">
Public Function timedelta(Optional weeks As Integer = 0, Optional days As Integer = 0, _
Public Function timedelta(Optional weeks As Integer = 0, Optional days As Integer = 0, _
Optional hours As Integer = 0, Optional minutes As Integer = 0, Optional seconds As Integer = 0, _
Optional hours As Integer = 0, Optional minutes As Integer = 0, Optional seconds As Integer = 0, _
Line 2,050: Line 2,050:
'-- timedelta(0,hours:=15,3) '-- illegal (it is not clear whether you meant days:=3 or minutes:=3)
'-- timedelta(0,hours:=15,3) '-- illegal (it is not clear whether you meant days:=3 or minutes:=3)
'VBA expects a named parameter for 3
'VBA expects a named parameter for 3
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|Visual Basic}}==
=={{header|Visual Basic}}==
<lang vb>'the function
<syntaxhighlight lang="vb">'the function
Sub whatever(foo As Long, bar As Integer, baz As Byte, qux As String)
Sub whatever(foo As Long, bar As Integer, baz As Byte, qux As String)
'...
'...
Line 2,060: Line 2,060:
Sub crap()
Sub crap()
whatever bar:=1, baz:=2, foo:=-1, qux:="Why is ev'rybody always pickin' on me?"
whatever bar:=1, baz:=2, foo:=-1, qux:="Why is ev'rybody always pickin' on me?"
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
Wren doesn't support named parameters as such though they can be simulated using a map.
Wren doesn't support named parameters as such though they can be simulated using a map.
<lang ecmascript>var printName = Fn.new { |name|
<syntaxhighlight lang="ecmascript">var printName = Fn.new { |name|
if (!(name is Map && name["first"] != null && name["last"] != null)) {
if (!(name is Map && name["first"] != null && name["last"] != null)) {
Fiber.abort("Argument must be a map with keys \"first\" and \"last\"")
Fiber.abort("Argument must be a map with keys \"first\" and \"last\"")
Line 2,073: Line 2,073:
printName.call({"first": "Abraham", "last": "Lincoln"}) // normal order
printName.call({"first": "Abraham", "last": "Lincoln"}) // normal order
printName.call({"last": "Trump", "first": "Donald"}) // reverse order
printName.call({"last": "Trump", "first": "Donald"}) // reverse order
printName.call({"forename": "Boris", "lastname": "Johnson"}) // wrong parameter names</lang>
printName.call({"forename": "Boris", "lastname": "Johnson"}) // wrong parameter names</syntaxhighlight>


{{out}}
{{out}}
Line 2,086: Line 2,086:
=={{header|XSLT}}==
=={{header|XSLT}}==
XSLT only allows specification of template parameters by name, not position.
XSLT only allows specification of template parameters by name, not position.
<lang xml><xsl:template name="table-header">
<syntaxhighlight lang="xml"><xsl:template name="table-header">
<xsl:param name="title"/>
<xsl:param name="title"/>
...
...
</xsl:template></lang>
</xsl:template></syntaxhighlight>
{{omit from|6502 Assembly|does not support named arguments without macros, which are entirely position-based}}
{{omit from|6502 Assembly|does not support named arguments without macros, which are entirely position-based}}
{{omit from|68000 Assembly|See above.}}
{{omit from|68000 Assembly|See above.}}