Named parameters: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(Add a Tcl example using dicts)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(11 intermediate revisions by 7 users not shown)
Line 16:
=={{header|11l}}==
 
<langsyntaxhighlight lang="11l">F sqlen(x = 0, y = 0, z = 0)
R x*x + y*y + z*z
 
print(sqlen(z' 3)) // equivalent to print(sqlen(0, 0, 3))</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight Adalang="ada">procedure Foo (Arg_1 : Integer; Arg_2 : Float := 0.0);</langsyntaxhighlight>
It can be equivalently called as:
<langsyntaxhighlight Adalang="ada">Foo (1, 0.0);
Foo (1);
Foo (Arg_2 => 0.0, Arg_1 => 1);
Foo (Arg_1 => 1);</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{trans|Lua}}
<langsyntaxhighlight lang="algol68">BEGIN
MODE OPTNAME = STRUCT(STRING name),
OPTSPECIES = STRUCT(STRING species),
Line 67:
print pet((NAME "Mike", SPECIES "Dog", BREED "Irish Setter", OWNER("Harry", "S.", "Truman")));
print pet(()) # use print pet((EMPTY)) for Algol 68G version 2 #
END</langsyntaxhighlight>
Output:
<pre>
Line 76:
=={{header|AppleScript}}==
AppleScript does not implement default or optional parameters, but they can be simulated using records.
<langsyntaxhighlight AppleScriptlang="applescript">on getName(x)
set {firstName, lastName} to {"?", "?"}
try
Line 86:
 
return firstName & ", " & lastName
end getName</langsyntaxhighlight>
Examples:
<langsyntaxhighlight AppleScriptlang="applescript ">getName({firstName:"John", lastName:"Doe"})
--> Returns: "John, Doe"
getName({lastName:"Doe"})
--> Returns: "?, Doe"</langsyntaxhighlight>
----
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:
 
<langsyntaxhighlight lang="applescript">on getName(x) -- x assumed to be a record for this demo.
set x to x & {firstName:"?", lastName:"?"}
 
Line 102:
 
getName({lastName:"Doe"})
--> "?, Doe"</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="applescript">on getName from firstName beside lastName
return firstName & ", " & lastName
end getName
 
getName beside "Doe" from "John"
--> "John, Doe"</langsyntaxhighlight>
 
However, it's also possible to define user labels, with the same flexibility of order, using a slightly different syntax:
 
<langsyntaxhighlight lang="applescript">on getName given firstName:firstName, lastName:lastName
return firstName & ", " & lastName
end getName
 
getName given lastName:"Doe", firstName:"John"
--> "John, Doe"</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="applescript">on getName given firstName:firstName, lastName:lastName, comma:comma
if (comma) then
return firstName & ", " & lastName
Line 135:
--> "John, Doe"
getName without comma given lastName:"Doe", firstName:"John"
--> "John Doe"</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight 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
Line 150:
 
getName given lastName:"Doe"
--> "Misc: ?, Doe"</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic"> 100 IF LAST$ = "" THEN PRINT "?";
110 IF LAST$ < > "" THEN PRINT LAST$;
120 IF FIRST$ < > "" THEN PRINT ", "FIRST$;
200 FIRST$ = ""
210 LAST$ = ""
220 RETURN</langsyntaxhighlight>
 
<pre>]FIRST$ = "JOHN" : GOSUB 100"PRINT NAME
Line 171:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">func: function [x][
print ["argument x:" x]
print ["attribute foo:" attr 'foo]
Line 182:
func .bar:"bar" 3
func .foo:123 .bar:124 4
func .bar:124 .foo:123 5</langsyntaxhighlight>
 
{{out}}
Line 209:
AutoHotkey doesn't have named parameters, but they can be simulated as follows.
ahk [http://www.autohotkey.com/forum/viewtopic.php?p=280499 discussion]
<langsyntaxhighlight AutoHotkeylang="autohotkey">MyFunc( "Val=0, w=1024, Text=The Quick Brown Fox, newVar=I'm New" )
 
MyFunc( _overrides="" ) {
Line 220:
Listvars
WinWaitClose, %A_ScriptFullPath%
}</langsyntaxhighlight>
 
=={{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 this task, the pattern is just made a bit more complex than would have been the case without explicit parameter names in the argument.
<langsyntaxhighlight lang="bracmat">( ( testproc
= i x y z
. out$"Calling testproc"
Line 244:
& testproc$((z,4) (x,2) (y,3)) { order is not important }
& testproc$((i,1) (y,2) (z,3))
);</langsyntaxhighlight>
Output:
<pre>Calling testproc
Line 260:
{{works with|C99}}
 
<langsyntaxhighlight lang="c">#include <stdio.h>
 
// 1. Named parameters
Line 307:
 
return 0;
}</langsyntaxhighlight>
 
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:
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.
 
<langsyntaxhighlight lang="csharp">using System;
 
namespace NamedParams
Line 336:
}
}
}</langsyntaxhighlight>
 
Output:
Line 350:
You wrap the parameters in a class, and make the function a friend of the parameter class.
 
<langsyntaxhighlight lang="cpp">class foo_params{
friend void foo(foo_params p);
public:
Line 376:
int optional_y_;
float optional_z_;
};</langsyntaxhighlight>
 
Declare the function to take the parameter class as its only parameter.
 
<langsyntaxhighlight lang="cpp">void foo(foo_params p){ . . .}</langsyntaxhighlight>
 
Call the function using the parameter object constructor with the required parameters and chaining the optional parameters.
 
<langsyntaxhighlight lang="cpp">foo(foo_params(42).x(7).z(23.54));</langsyntaxhighlight>
 
 
Line 390:
 
If you want real named parameters you can use The Boost Parameter Library.
<langsyntaxhighlight lang="cpp">#include <boost/parameter/name.hpp>
#include <boost/parameter/preprocessor.hpp>
#include <string>
Line 415:
if (baz && (bar > 1.0)) return foo;
return bonk.size();
}</langsyntaxhighlight>
 
Once the definition is written, using it is easy, by name or position.
 
<langsyntaxhighlight lang="cpp">function_with_named_parameters(1, 10.0);
function_with_named_parameters(7, _bar = 3.14);
function_with_named_parameters( _bar = 0.0, _foo = 42);
function_with_named_parameters( _bar = 2.5, _bonk= "Hello", _foo = 9);
function_with_named_parameters(9, 2.5, true, "Hello");</langsyntaxhighlight>
 
=={{header|Clojure}}==
Line 429:
Clojure doesn't have built-in support for named or keyword arguments, but you can use destructuring to achieve a similar effect.
 
<langsyntaxhighlight lang="clojure">(defn foo [& opts]
(let [opts (merge {:bar 1 :baz 2} (apply hash-map opts))
{:keys [bar baz]} opts]
[bar baz]))</langsyntaxhighlight>
 
Clojure 1.2 supports destructuring of trailing arguments as a map:
 
<langsyntaxhighlight lang="clojure">(defn foo [& {:keys [bar baz] :or {bar 1, baz 2}}]
[bar baz])</langsyntaxhighlight>
 
You can also use <code>defnk</code> from <code>clojure.contrib.def</code>, which is a macro that works similarly.
 
<langsyntaxhighlight lang="clojure">(use 'clojure.contrib.def)
(defnk foo [:bar 1 :baz 2]
[bar baz])</langsyntaxhighlight>
 
Sample output for all variants:
Line 457:
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun print-name (&key first (last "?"))
(princ last)
(when first
(princ ", ")
(princ first))
(values))</langsyntaxhighlight>
 
<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).
 
<langsyntaxhighlight lang="lisp">CL-USER> (print-name)
?
CL-USER> (print-name :first "John")
Line 473:
Doe, John
CL-USER> (print-name :last "Doe")
Doe</langsyntaxhighlight>
 
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:
{{Trans|C++}}
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;
 
Line 538:
 
{$IFNDEF UNIX} readln; {$ENDIF}
end.</langsyntaxhighlight>
 
=={{header|Dyalect}}==
Line 544:
Dyalect supports both named and optional parameters.
 
<langsyntaxhighlight lang="dyalect">func fun(x, y = 0, z = 12.2, dsc = "Useless text") {
print("x=\(x), y=\(y), z=\(z), dsc=\(dsc)")
}
 
fun(12, z: 24.4, dsc: "Foo", y: 3)
fun(y: 42, x: 12)</langsyntaxhighlight>
 
{{out}}
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.
 
<langsyntaxhighlight lang="e">def printName([=> first := null, => last := null]) {
if (last == null) {
print("?")
Line 570:
print(first)
}
}</langsyntaxhighlight>
 
(Note: In map literals and map patterns, “<code>=> <var>x</var></code>” is shorthand for “<code>"<var>x</var>" => <var>x</var></code>”.)
 
<langsyntaxhighlight lang="e">? printName(["first" => "John"])
?, John
 
Line 581:
 
? printName(["first" => "John", "last" => "Doe"])
Doe, John</langsyntaxhighlight>
 
=={{header|Ecstasy}}==
Method and function arguments are passed in order, unless argument names are specified by the caller. Both named arguments and default values for arguments are supported. Ordered and named arguments can both be used in the same invocation, but once a named argument is specified, all subsequent arguments in the invocation must also be named.
 
A common example of using named arguments is a "wither" method:
<syntaxhighlight lang="java">
module NamedParams {
const Point(Int x, Int y) {
Point with(Int? x=Null, Int? y=Null) {
return new Point(x ?: this.x, y ?: this.y);
}
}
 
@Inject Console console;
 
void run() {
Point origin = new Point(0, 0);
console.print($"origin={origin}");
Point moveRight = origin.with(x=5);
console.print($"moveRight(x=5)={moveRight}");
Point moveUp = moveRight.with(y=3);
console.print($"moveUp(y=3)={moveUp}");
}
}
</syntaxhighlight>
 
{{out}}
<pre>
origin=(x=0, y=0)
moveRight(x=5)=(x=5, y=0)
moveUp(y=3)=(x=5, y=3)
</pre>
 
=={{header|Elixir}}==
Line 587 ⟶ 619:
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}."
 
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.
Line 597 ⟶ 629:
=={{header|Erlang}}==
At a guess "named parameters" are supposed to be used like proplists in Erlang.
<syntaxhighlight lang="erlang">
<lang Erlang>
Fun = fun( Proplists ) ->
Argument1 = proplists:get_value( argument1, Proplists, 1 ),
Line 603 ⟶ 635:
io:fwrite( "~p ~s~n", [Argument1, Kalle] )
end.
</syntaxhighlight>
</lang>
 
The function can now be called like these examples.
Line 614 ⟶ 646:
9 gustav
</pre>
 
=={{header|F Sharp|F#}}==
 
F# supports named method arguments directly. However they are not supported for functions, function values, or lambda functions.
 
This example comes from the F# documentation:
<syntaxhighlight lang="fsharp">
type SpeedingTicket() =
member this.GetMPHOver(speed: int, limit: int) = speed - limit
 
let CalculateFine (ticket : SpeedingTicket) =
let delta = ticket.GetMPHOver(limit = 55, speed = 70)
if delta < 20 then 50.0 else 100.0
 
let ticket1 : SpeedingTicket = SpeedingTicket()
printfn "%f" (CalculateFine ticket1)
</syntaxhighlight>
 
=={{header|Factor}}==
Line 619 ⟶ 668:
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 * ;
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
Line 629 ⟶ 678:
 
{{works with|Gforth}}
<langsyntaxhighlight lang="forth">256 buffer: first-name
256 buffer: last-name
: is ( a "name" -- ) parse-name rot place ;
Line 649 ⟶ 698:
cr ." Hiya, " given-name $. space surname $. ." !" ;
 
Person new >o s" Bob" given-name $! s" Hall" surname $! hiya o></langsyntaxhighlight>
 
{{out}}<pre>Hello, Bob Hall!
Line 659 ⟶ 708:
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.
 
<langsyntaxhighlight lang="fortran">subroutine a_sub(arg1, arg2, arg3)
integer, intent(in) :: arg1, arg2
integer, intent(out), optional :: arg3
! ...
end subroutine a_sub</langsyntaxhighlight>
 
<langsyntaxhighlight lang="fortran">! usage
integer :: r
call a_sub(1,2, r)
call a_sub(arg2=2, arg1=1)</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="fortran">subroutine b_sub(arg1, arg2)
integer, intent(in), optional :: arg1
integer, intent(in) :: arg2
!...
end subroutine b_sub</langsyntaxhighlight>
 
<langsyntaxhighlight lang="fortran">call b_sub(1) ! error: missing non optional arg2
call b_sub(arg2=1) ! ok
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</langsyntaxhighlight>
 
 
=={{header|FreeBASIC}}==
{{trans|Visual Basic}}
<langsyntaxhighlight lang="freebasic">Dim Shared foo As Long, bar As Integer, baz As Byte, qux As String
'la función
Sub LoqueSea(foo As Long, bar As Integer, baz As Byte, qux As String)
Line 695 ⟶ 744:
Sub Algo()
LoqueSea(bar = 1, baz = 2, foo = -1, qux = "Probando")
End Sub</langsyntaxhighlight>
 
 
Line 704 ⟶ 753:
 
Here's a simple example.
<langsyntaxhighlight lang="go">package main
 
import (
Line 723 ⟶ 772:
t := myFunc(params{y: 2}) // only one field, others set to zero
fmt.Println("t =", t)
}</langsyntaxhighlight>
 
{{out}}
Line 735 ⟶ 784:
We can simulate named, but not moveable arguments, with nullary data constructors:
 
<langsyntaxhighlight Haskelllang="haskell">data X = X
data Y = Y
data Point = Point Int Int deriving Show
Line 742 ⟶ 791:
createPointAt X x Y y = Point x y
 
main = print $ createPointAt X 5 Y 3</langsyntaxhighlight>
 
We can also emulate named, moveable, optional arguments with record syntax:
 
<langsyntaxhighlight Haskelllang="haskell">data Point = Point {x, y :: Int} deriving Show
defaultPoint = Point {x = 0, y = 0}
 
createPointAt :: Point -> Point
createPointAt = id
main = print $ createPointAt (defaultPoint { y = 3, x = 5 })</langsyntaxhighlight>
 
Though this is cumbersome without using template Haskell, as the call site must supply the defaults.
Line 764 ⟶ 813:
 
 
<langsyntaxhighlight Iconlang="icon">procedure main()
testproc("x:=",1,"y:=",2,"z:=",3)
testproc("x:=",3,"y:=",1,"z:=",2)
Line 783 ⟶ 832:
write(" y:=",y)
write(" z:=",z)
end</langsyntaxhighlight>
{{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 ⟶ 854:
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:
 
<langsyntaxhighlight lang="j">NB. Strand notation
myFunc['c:\file.txt' 906 'blue' fs]
 
Line 830 ⟶ 879:
 
NB. Even the delimiters are flexible...
myFunc<MAX=906, COLOR=blue fs></langsyntaxhighlight>
 
For further discussion, see the [http://www.jsoftware.com/pipermail/programming/2009-July/015571.html corresponding thread in the J Forums].
Line 836 ⟶ 885:
=={{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])
<langsyntaxhighlight lang="java">processNutritionFacts(new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build());</langsyntaxhighlight>
Follow the link for extra details about the 'NutritionFacts' class example.
 
=={{header|JavaScript}}==
JavaScript only has positional parameters, but named parameters can be emulated by passing an object with the appropriate properties:
<langsyntaxhighlight lang="javascript">function example(options) {
// assign some defaults where the user's has not provided a value
opts = {}
Line 852 ⟶ 901:
 
example({grill: "lamb kebab", bar: 3.14});
// => "foo is 0, bar is 3.14, and grill is lamb kebab"</langsyntaxhighlight>
===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):<langsyntaxhighlight lang="javascript">let
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.
Line 865 ⟶ 914:
// foo is 0 , bar is 3.14 , and grill is lamb kebab
example({foo:null});
// foo is , bar is 1 , and grill is pork chops</langsyntaxhighlight>
 
=={{header|jq}}==
Line 871 ⟶ 920:
 
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):
({ "name": "?"} + obj) as $obj # the default default value is null
Line 879 ⟶ 928:
else $name + ", " + $first
end;
</syntaxhighlight>
</lang>
 
Here are examples of how the function can be invoked:
<syntaxhighlight lang="jq">
<lang jq>
formatName({"first": "George", "name": "Eliot"})
 
Line 892 ⟶ 941:
 
formatName({})
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
Julia supports arbitrary named keyword arguments, which are listed (with their default values) after a <code>;</code> in the function definition:
<langsyntaxhighlight Julialang="julia">function surround(string ; border = :default, padding = 0)
 
ve, ho, ul, ur, dl, dr =
border == :round ? ("\u2502","\u2500","\u256d","\u256e","\u2570","\u256f") :
border == :bold ? ("\u2503","\u2501","\u250F","\u2513","\u2517","\u251b") :
border == :double ? ("\u2551","\u2550","\u2554","\u2557","\u255a","\u255d") :
border == :dotted ? ("\u254e","\u254c","\u250c","\u2510","\u2514","\u2518") :
border == :cross ? ("\u2502","\u2500","\u253c","\u253c","\u253c","\u253c") :
("\u2502","\u2500","\u250c","\u2510","\u2514","\u2518")
 
println(ul, ho^(length(string) + 2padding), ur, "\n",
ve, " "^padding, string," "^padding, ve, "\n",
dl, ho^(length(string) + 2padding), dr)
end</langsyntaxhighlight>
 
{{Out}}
Line 923 ⟶ 972:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun someFunction(first: String, second: Int = 2, third: Double) {
Line 941 ⟶ 990:
// using first and third parameters in reverse
someFunction(third = 2.0, first = "reversed")
}</langsyntaxhighlight>
 
{{out}}
Line 960 ⟶ 1,009:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define mymethod(
-first::integer, // with no default value the param is required
-second::integer,
Line 975 ⟶ 1,024:
-first = 54,
-delimiter = '#'
)</langsyntaxhighlight>
-> 54:45
 
Line 982 ⟶ 1,031:
=={{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:
<langsyntaxhighlight lang="lingo">-- accepts either 3 integers or a single property list
on foo (arg1, arg2, arg3)
if ilk(arg1)=#propList then
Line 1,003 ⟶ 1,052:
-- "arg1="
-- "arg2="
-- "arg3=3"</langsyntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">
<lang Lua>
function CreatePet(options)
local name=options.name
Line 1,015 ⟶ 1,064:
CreatePet{name='Rex',species='Dog',breed='Irish Setter'}
--position does not matter here.
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
Line 1,021 ⟶ 1,070:
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) {
Print type$(x), x
Line 1,036 ⟶ 1,085:
}
namedparam %x=1, %y=1
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">f := proc(a, {b:= 1, c:= 1})
print (a*(c+b));
end proc:
Line 1,048 ⟶ 1,097:
3
f(2, b = 5, c = 3);#b and c can be put in any order
16</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Options[fn]={Add->False,Offset-> 0};
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,{Offset->2,Add->True}]</langsyntaxhighlight>
{{out}}
<pre>9
Line 1,063 ⟶ 1,112:
Named parameters are not natively supported. However, the following code can be used to implement them.
 
<langsyntaxhighlight Matlablang="matlab"> function foo(varargin)
for k= 1:2:length(varargin);
switch (varargin{k})
Line 1,077 ⟶ 1,126:
 
foo('param1','a1','param2','b2');
foo('param2','b2','param1','a1'); </langsyntaxhighlight>
 
Output:
Line 1,090 ⟶ 1,139:
Much like [[Ada]], Modula-3 allows either positional or keyed association of actual parameters. Defaults can also be ignored.
 
<langsyntaxhighlight lang="modula3">PROCEDURE Foo(Arg1: INTEGER; Arg2: REAL := 0.0);</langsyntaxhighlight>
It can be equivalently called as:
<langsyntaxhighlight lang="modula3">Foo(1, 0.0);
Foo(1);
Foo(Arg2 := 0.0, Arg1 := 1);
Foo(Arg1 := 1);</langsyntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="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(3, option = false, word = "Bird") // unnamed arguments must be in same order as function definition and precede named arguments
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
In Nim, a regular parameter of a procedure can be used as either a positional or a named parameter.
 
<langsyntaxhighlight lang="nim">proc subtract(x, y): auto = x - y
 
echo subtract(5, 3) # used as positional parameters
echo subtract(y = 3, x = 5) # used as named parameters</langsyntaxhighlight>
 
Parameters can be made optional by providing a default argument.
Line 1,116 ⟶ 1,165:
=={{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.)
<langsyntaxhighlight lang="objc">@interface Demo : NSObject {
// Omitted ...
}
Line 1,123 ⟶ 1,172:
- (double) hypotenuseOfX: (double)x andY: (double)y andZ: (double)z;
 
@end</langsyntaxhighlight>
<langsyntaxhighlight lang="objc">@implementation Demo
 
- (double) hypotenuseOfX: (double)x andY: (double)y {
Line 1,133 ⟶ 1,182:
}
 
@end</langsyntaxhighlight>
<langsyntaxhighlight lang="objc">Demo *example = [[Demo alloc] init];
double h = [example hypotenuseOfX:1.23 andY:3.79];</langsyntaxhighlight>
Note in the example above that the name of the method, the ''selector''; is actually “<code>hypotenuseOfX:andY:</code>”.
 
=={{header|OCaml}}==
You can make a named argument (called ''labels'' in OCaml) by putting a tilde (~) before the name:
<langsyntaxhighlight lang="ocaml"># let foo ~arg1 ~arg2 = arg1 + arg2;;
val foo : arg1:int -> arg2:int -> int = <fun>
 
Line 1,147 ⟶ 1,196:
 
# foo ~arg2:17 ~arg1:42;;
- : int = 59</langsyntaxhighlight>
 
Named arguments can be re-ordered, but two arguments of the same label cannot be re-ordered relative to each other.
Line 1,157 ⟶ 1,206:
=={{header|Oz}}==
For <b>methods</b>, Oz does support named parameters with default values. The named parameters can be freely reordered.
<langsyntaxhighlight lang="oz">declare
class Foo
meth init skip end
Line 1,171 ⟶ 1,220:
{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"</langsyntaxhighlight>
 
For <b>procedures</b> only positional parameters are supported. However, you can emulate named parameters by using records:
<syntaxhighlight lang="oz">
<lang oz>
declare
proc {Foo PP Other=unit(named1:N1 named2:N2 ...)}
Line 1,184 ⟶ 1,233:
{Foo 1 unit(named1:2 named2:3 namedWithDefault:4)}
{Foo 1 unit(named2:2 named1:3)}
{Foo 1 unit(named1:2)} %% not ok...</langsyntaxhighlight>
 
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 ⟶ 1,242:
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.
 
<langsyntaxhighlight lang="perl">sub funkshun {
my %h = @_;
# Print every argument and its value.
Line 1,204 ⟶ 1,253:
# Otherwise, say that it's off.
print "Safe mode ", ($h{safe} ? 'on' : 'off'), ".\n";
}</langsyntaxhighlight>
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:
 
<langsyntaxhighlight lang="perl">funkshun(
verbosity => 3,
password => 'foobie blech',
Line 1,213 ⟶ 1,262:
'42' => 'answer',
password => 'joshua'
);</langsyntaxhighlight>
Its output:
 
Line 1,223 ⟶ 1,272:
Safe mode off.</pre>
 
Further flexibility can be obtained by using [[Pass by reference]] semantics:<langsyntaxhighlight Perllang="perl">sub event
{
my ($params_ref, $name) = @_;
Line 1,259 ⟶ 1,308:
},
"Joe Schmoe"
);</langsyntaxhighlight>Prints:
<pre>
Joe Schmoe called event() with the following named parameters:
Line 1,275 ⟶ 1,324:
=={{header|Phix}}==
{{libheader|Phix/basics}}
Phix supports named and optional parameters in a very simple, natural, and intuitive way, erring on the side of caution when faced with any potential ambiguity.<br>
Optional parameters are specified simply byany providingwith a default, and any non-defaulted parameters must occur before (to the left of) any defaulted parameterssuch.<br>
Named parameters can be given (when invoking a routine)provided in any order, but must be grouped together after (to the right of) any non-namedpositional parameters.<br>
Note that low-level builtins (those defined using AutoAsm() in psym.e/syminit()) do not [yet] support named parameters (maybe one day..), but everything else does.
 
The classic example (inspired by the standard Python equivalent) is that builtins\timedate.e defines:
<!--<langsyntaxhighlight Phixlang="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>
<!--</langsyntaxhighlight>-->
 
which can be invoked as follows:
 
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #000000004080;">timedate</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">days</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hours</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span>
 
<span style="color: #008080;">constant</span> <span style="color: #000000;">fourdays</span> <span style="color: #0000FF;">=</span> <span style="color: #0000007060A8;">timedelta</span><span style="color: #0000FF;">(</span><span style="color: #000000;">days</span><span style="color: #0000FF;">:=</span><span style="color: #000000;">4</span><span style="color: #0000FF;">),</span>
<span style="color: #000080;font-style:italic;">-- fourdays = timedelta(0,4) -- equivalent, **NB** a plain '=' is a very different thing:</span>
<span style="color: #000000;">slipup</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">timedelta</span><span style="color: #0000FF;">(</span><span style="color: #000000;">days</span><span style="color: #0000FF;">=</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- === timedelta([weeks:=]iff(equal(days,4)?true:false))
 
-- with error if no local/in scope identifier days exists.</span>
<span style="color: #000000;">shift</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">timedelta</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hours</span><span style="color: #0000FF;">:=</span><span style="color: #000000;">hours</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- perfectly valid (param hours:=local hours)
-- timedelta(0,hours:=15,3) -- illegal (not clear whether days:=3 or minutes:=3)
-- though of course the weeks:=0 part is fine</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;">"fourdays = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fourdays</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;">"wrong = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">slipup</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>
<!--</syntaxhighlight>-->
 
<span style="color: #000080;font-style:italic;">-- **NB** a plain '=' is a very different thing:</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">days</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">wrong</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">timedelta</span><span style="color: #0000FF;">(</span><span style="color: #000000;">days</span><span style="color: #0000FF;">=</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- equivalent to timedelta([weeks:=]iff((equal(days,4)?true:false))
-- - with an error if no local variable days exists.</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;">"wrong = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">oneday</span><span style="color: #0000FF;">)})</span>
 
<span style="color: #004080;">integer</span> <span style="color: #000000;">hours</span><span style="color: #0000FF;">=</span><span style="color: #000000;">7</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">shift</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">timedelta</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hours</span><span style="color: #0000FF;">:=</span><span style="color: #000000;">hours</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- perfectly valid (param hours:=local hours)
-- timedelta(0,hours:=15,3) -- illegal (it is not clear whether you meant days:=3 or minutes:=3)</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>-->
Note that pwa/p2js automatically maps named parameters to positional parameters for you, since JavaScript does not support named parameters.
{{out}}
Line 1,319 ⟶ 1,363:
=={{header|PHP}}==
PHP doesn't support named parameters but you can simulate the behavior with PHP arrays.
<langsyntaxhighlight PHPlang="php">function named($args) {
$args += ["gbv" => 2,
"motor" => "away",
Line 1,326 ⟶ 1,370:
}
 
named(["teenage" => "cia", "gbv" => 10]);</langsyntaxhighlight>
Output:
<pre>10 men running away from the cia</pre>
Line 1,335 ⟶ 1,379:
to establish bindings to passed names.
===Passing symbol-value pairs===
<langsyntaxhighlight PicoLisplang="picolisp">(de foo @
(bind (rest) # Bind symbols in CARs to values in CDRs
(println 'Bar 'is Bar)
(println 'Mumble 'is Mumble) ) )
 
(foo '(Bar . 123) '(Mumble . "def"))</langsyntaxhighlight>
===Passing a name list followed by values===
<langsyntaxhighlight PicoLisplang="picolisp">(de foo @
(bind (next) # Save all symbols in first argument
(mapc set (arg) (rest)) # then bind them to remaining arguments
Line 1,348 ⟶ 1,392:
(println 'Mumble 'is Mumble) ) )
 
(foo '(Bar Mumble) 123 "def")</langsyntaxhighlight>
Output in both cases:
<pre>Bar is 123
Line 1,356 ⟶ 1,400:
===Positional parameters===
When writing a function and not stating any parameters explicitly, such as the following function
<langsyntaxhighlight lang="powershell">function Test {
Write-Host Argument 1 is $args[0]
}</langsyntaxhighlight>
the only option are positional parameters using the <code>$args</code> array.
===Named parameters===
Stating any number of parameters directly in the function definition, such as
<langsyntaxhighlight lang="powershell">function Test ($SomeArgument, $AnotherArgument, $ThirdArgument) {
Write-Host "Some argument: $SomeArgument"
Write-Host "Another argument: $AnotherArgument"
Write-Host "Third argument: $ThirdArgument"
}</langsyntaxhighlight>
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
Line 1,382 ⟶ 1,426:
===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.
<langsyntaxhighlight lang="powershell">function SwitchTest ([switch] $on) {
Write-Host Switched $(if ($on) { "on" } else { "off" })
}</langsyntaxhighlight>
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
Line 1,392 ⟶ 1,436:
===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:
<langsyntaxhighlight lang="powershell">function Greeting ($Name = "Nobody") {
Write-Host Hello, $Name!
}</langsyntaxhighlight>
If the <code>Name</code> argument is omitted now, its value will be <code>"Nobody"</code> instead of <code>$null</code>:
<pre>PS> Greeting
Line 1,403 ⟶ 1,447:
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<langsyntaxhighlight lang="prolog">:- initialization(main).
 
main :-
Line 1,417 ⟶ 1,461:
member(A,C),
named_args(B,C).
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
Line 1,425 ⟶ 1,469:
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.
 
<langsyntaxhighlight lang="python">def subtract(x, y):
return x - y
 
subtract(5, 3) # used as positional parameters; evaluates to 2
subtract(y = 3, x = 5) # used as named parameters; evaluates to 2</langsyntaxhighlight>
 
Parameters can be made optional by providing a default argument, as described in the [[optional parameters]] article.
Line 1,486 ⟶ 1,530:
 
====Examples====
<langsyntaxhighlight lang="python">>>> from __future__ import print_function
>>>
>>> def show_args(defparam1, defparam2 = 'default value', *posparam, **keyparam):
Line 1,592 ⟶ 1,636:
'EXTRA', 'POSITIONAL', 'ARGUMENTS')
SyntaxError: non-keyword arg after keyword arg
>>></langsyntaxhighlight>
 
=={{header|R}}==
Line 1,598 ⟶ 1,642:
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.
 
<langsyntaxhighlight lang="rsplus">divide <- function(numerator, denominator) {
numerator / denominator
}
Line 1,607 ⟶ 1,651:
divide(den=3, num=2) # 0.66
divide(den=3, 2) # 0.66
divide(3, num=2) # 0.66</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 1,613 ⟶ 1,657:
Racket has built-in keyword and optional arguments:
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 1,626 ⟶ 1,670:
(pizza "tomato" #:topping "onion")
(pizza #:topping "onion" "garlic" #:type "pan")
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 1,634 ⟶ 1,678:
Raku's support for optional parameters is much like Python's. Consider this declaration:
 
<syntaxhighlight lang="raku" perl6line>sub funkshun ($a, $b?, $c = 15, :$d, *@e, *%f) {
...
}</langsyntaxhighlight>
 
In the above signature:
Line 1,648 ⟶ 1,692:
So, if we defined the function like this:
 
<syntaxhighlight lang="raku" perl6line>sub funkshun ($a, $b?, :$c = 15, :$d, *@e, *%f) {
say "$a $b $c $d";
say join ' ', @e;
Line 1,658 ⟶ 1,702:
funkshun
'Alfa', k1 => 'v1', c => 'Charlie', 'Bravo', 'e1',
d => 'Delta', 'e2', k2 => 'v2';</langsyntaxhighlight>
 
would print this:
Line 1,668 ⟶ 1,712:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/*REXX pgm shows named parameters when called as a subroutine/function*/
/*┌────────────────────────────────────────────────────────────────────┐
│ The syntax of: xxx = func1(parmName2=arg2, parmName1=arg1) │
Line 1,743 ⟶ 1,787:
 
return 'the final meaning of life, or 42 --- whichever is appropriate.'
/*stick a fork in it, we're done.*/</langsyntaxhighlight>
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 01.07.2014 Walter Pachl
* Argument values must not start with 'arg'
Line 1,765 ⟶ 1,809:
Say 'p.'i'='p.i
End
Return p.1**p.2</langsyntaxhighlight>
{{Out}}
<pre>p.1=2
Line 1,780 ⟶ 1,824:
{{trans|Tcl}}
{{works with|Ruby|2.0}}
<langsyntaxhighlight lang="ruby">def example(foo: 0, bar: 1, grill: "pork chops")
puts "foo is #{foo}, bar is #{bar}, and grill is #{grill}"
end
 
# Note that :foo is omitted and :grill precedes :bar
example(grill: "lamb kebab", bar: 3.14)</langsyntaxhighlight>
 
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 ⟶ 1,835:
{{works with|Ruby|1.9}}
 
<langsyntaxhighlight lang="ruby">def example(opts = {})
# Hash#merge raises TypeError if _opts_ is not a Hash.
# Nothing checks if _opts_ contains unknown keys.
Line 1,801 ⟶ 1,845:
end
 
example(grill: "lamb kebab", bar: 3.14)</langsyntaxhighlight>
 
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 = {})
defaults = {:foo => 0, :bar => 1, :grill => "pork chops"}
opts = defaults.merge(opts)
printf("foo is %s, bar is %s, and grill is %s\n",
opts[:foo], opts[:bar], opts[:grill])
end
 
example(:grill => "lamb kebab", :bar => 3.14)</lang>
 
{{omit from|Rust}}
Line 1,820 ⟶ 1,853:
Scala 2.8 utilizes named parameters and default values:
 
<langsyntaxhighlight lang="scala">
def add(x: Int, y: Int = 1) = x + y
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight lang="scala">
scala> add(5)
6
Line 1,830 ⟶ 1,863:
scala> add(y=10, x=4)
14
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">
(define (keyarg-parser argdefs args kont)
(apply kont
Line 1,855 ⟶ 1,888:
(display first)))
(newline))))
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight lang="scheme">
=> (print-name)
?
Line 1,866 ⟶ 1,899:
=>(print-name 'last "Doe")
Doe
</syntaxhighlight>
</lang>
 
=={{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.<langsyntaxhighlight lang="sensetalk">introduce "Mary"
introduce "Pablo", "Hola"
introduce greeting:"Bonjour", name:"Brigitte" by name
Line 1,876 ⟶ 1,909:
put greeting && name
end introduce
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,885 ⟶ 1,918:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func example(foo: 0, bar: 1, grill: "pork chops") {
say "foo is #{foo}, bar is #{bar}, and grill is #{grill}";
}
 
# Note that :foo is omitted and :grill precedes :bar
example(grill: "lamb kebab", bar: 3.14);</langsyntaxhighlight>
{{out}}
<pre>foo is 0, bar is 3.14, and grill is lamb kebab</pre>
Line 1,900 ⟶ 1,933:
{{works with|GNU Smalltalk}}
 
<langsyntaxhighlight lang="smalltalk">Object subclass: AnotherClass [
"..."
initWithArray: anArray [ "single argument" ]
Line 1,908 ⟶ 1,941:
]
"..."
]</langsyntaxhighlight>
 
=={{header|Standard ML}}==
This example uses Standard ML "fields".
<langsyntaxhighlight 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)</langsyntaxhighlight>
 
To call the procedure ''example'', use:
<langsyntaxhighlight lang="sml">example {a="Hello World!", b=3.14, c=42}</langsyntaxhighlight>
However, this does not support optional parameters. To emulate them, we can process a parameter list:
<langsyntaxhighlight lang="sml">datatype param = A of string | B of real | C of int
 
fun args xs =
Line 1,930 ⟶ 1,963:
map (fn (A x) => a := x | (B x) => b := x | (C x) => c := x) xs;
(!a, !b, !c)
end</langsyntaxhighlight>
To process the argument list and call ''example'', use:
<langsyntaxhighlight lang="sml">dosomething (args [A "tam", B 42.0]);</langsyntaxhighlight>
 
=={{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.
<syntaxhighlight lang="suneido">
<lang Suneido>
test = function (one, two, three = '', four = '', five = '')
{
Line 1,943 ⟶ 1,976:
}
test('1', '2', five: '5', three: '3')
</syntaxhighlight>
</lang>
Output:
<langsyntaxhighlight Suneidolang="suneido">one: 1, two: 2, three: 3, four: , five: 5</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight Swiftlang="swift">func greet(person: String, hometown: String) -> String {
return "Hello \(person)! Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", hometown: "Cupertino"))</langsyntaxhighlight>
You write an argument label before the parameter name, separated by a space:
<langsyntaxhighlight Swiftlang="swift">func greet(person: String, from hometown: String) -> String {
return "Hello \(person)! Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", from: "Cupertino"))</langsyntaxhighlight>
 
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.
<langsyntaxhighlight Swiftlang="swift">func greet(_ person: String, _ hometown: String) -> String {
return "Hello \(person)! Glad you could visit from \(hometown)."
}
print(greet("Bill", "Cupertino"))</langsyntaxhighlight>
 
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.
<langsyntaxhighlight Swiftlang="swift">func greet(person: String, from hometown: String = "Cupertino") -> String {
return "Hello \(person)! Glad you could visit from \(hometown)."
}
print(greet(person: "Bill"))</langsyntaxhighlight>
 
=={{header|Tcl}}==
===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.
<langsyntaxhighlight lang="tcl">proc example args {
# Set the defaults
array set opts {-foo 0 -bar 1 -grill "hamburger"}
Line 1,986 ⟶ 2,019:
# Note that -foo is omitted and -grill precedes -bar
example -grill "lamb kebab" -bar 3.14
# => ‘foo is 0, bar is 3.14, and grill is lamb kebab’</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="tcl">package require opt
tcl::OptProc example {
{-foo -int 0 "The number of foos"}
Line 2,005 ⟶ 2,038:
# -foo int (0) The number of foos
# -bar float (1.0) How much bar-ness
# -grill any (hamburger) What to cook on the grill</langsyntaxhighlight>
 
According to [http://wiki.tcl.tk/1730 wiki.tcl.tk discussions], '''::tcl::OptProc is deprecated.'''
Line 2,012 ⟶ 2,045:
===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):
<langsyntaxhighlight lang="tcl">proc example {x y args} {
set keyargs {arg1 default1 arg2 default2}
if {[llength $args] % 2 != 0} {
Line 2,027 ⟶ 2,060:
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 # => test: invalid keyword arguments (spec: arg1 default1 arg2 default2)</langsyntaxhighlight>
 
Of course, more work is required to reach the flexibility of something like Common Lisp's ordinary lambda list.
Line 2,033 ⟶ 2,066:
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight lang="vb">
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, _
Line 2,050 ⟶ 2,083:
'-- 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
End Sub</langsyntaxhighlight>
 
=={{header|Visual Basic}}==
<langsyntaxhighlight lang="vb">'the function
Sub whatever(foo As Long, bar As Integer, baz As Byte, qux As String)
'...
Line 2,060 ⟶ 2,093:
Sub crap()
whatever bar:=1, baz:=2, foo:=-1, qux:="Why is ev'rybody always pickin' on me?"
End Sub</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
1) Vlang allows for a struct literal to be passed to the function, instead of named parameters.
 
2) Using this style, fields need not appear in the same order as they are declared.
 
3) If one or more fields are omitted, their default values will be used instead.
 
4) The named parameter feature was deliberately omitted, for greater code readability.
 
5) Depending on the situation, variadic and/or sum types can also be considered.
<syntaxhighlight lang="Zig">
struct Params {
a int
b int
c int
}
 
fn a_fn(p Params) int {
return p.a + p.b + p.c
}
 
fn main() {
x := a_fn(Params{a: 1, b: 2, c: 3}) // same order
println("x = ${x}")
y := a_fn(Params{c: 3, b: 2, a: 1}) // different order
println("y = ${y}")
z := a_fn(Params{c: 2}) // only one field
println("z = ${z}")
}
</syntaxhighlight>
 
{{out}}
<pre>
x = 6
y = 6
z = 2
</pre>
 
=={{header|Wren}}==
Wren doesn't support named parameters as such though they can be simulated using a map.
<langsyntaxhighlight ecmascriptlang="wren">var printName = Fn.new { |name|
if (!(name is Map && name["first"] != null && name["last"] != null)) {
Fiber.abort("Argument must be a map with keys \"first\" and \"last\"")
Line 2,073 ⟶ 2,145:
printName.call({"first": "Abraham", "last": "Lincoln"}) // normal order
printName.call({"last": "Trump", "first": "Donald"}) // reverse order
printName.call({"forename": "Boris", "lastname": "Johnson"}) // wrong parameter names</langsyntaxhighlight>
 
{{out}}
Line 2,086 ⟶ 2,158:
=={{header|XSLT}}==
XSLT only allows specification of template parameters by name, not position.
<langsyntaxhighlight lang="xml"><xsl:template name="table-header">
<xsl:param name="title"/>
...
</xsl:template></langsyntaxhighlight>
{{omit from|6502 Assembly|does not support named arguments without macros, which are entirely position-based}}
{{omit from|68000 Assembly|See above.}}
Line 2,098 ⟶ 2,170:
{{omit from|bc}}
{{omit from|dc}}
{{omit from|F_sharp}}
{{omit from|GUISS}}
{{omit from|Joy}}
9,485

edits