Named parameters: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Perl 6.)
m (Fixed lang tags.)
Line 49: Line 49:
Doe, John
Doe, John
CL-USER> (print-name :last "Doe")
CL-USER> (print-name :last "Doe")
Doe
Doe</lang>
</lang>


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 88: Line 87:
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)
<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</lang>


<lang fortran>! usage
<lang fortran>! usage
Line 101: Line 100:
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)
<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</lang>


<lang fortran> call b_sub(1) ! error: missing non optional arg2
<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</lang>


=={{header|J}}==
=={{header|J}}==
Line 116: Line 115:
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:


NB. Strand notation
<lang j>NB. Strand notation
myFunc['c:\file.txt' 906 'blue' fs]
myFunc['c:\file.txt' 906 'blue' fs]
NB. Commas, like other langs
NB. Commas, like other langs
myFunc['c:\file.txt', 906, 'blue' fs]
myFunc['c:\file.txt', 906, 'blue' fs]
NB. Unspecified args are defaulted ("optional")
NB. Unspecified args are defaulted ("optional")
myFunc['c:\file.txt' fs]
myFunc['c:\file.txt' fs]
NB. Can use named arguments, like eg VB
NB. Can use named arguments, like eg VB
myFunc[color='blue' fs]
myFunc[color='blue' fs]
NB. Often values needn't be quoted
NB. Often values needn't be quoted
myFunc[color= blue fs]
myFunc[color= blue fs]
NB. Combination of comma syntax and name=value
NB. Combination of comma syntax and name=value
myFunc[max=906, color=blue fs]
myFunc[max=906, color=blue fs]
NB. Spelling of names is flexible
NB. Spelling of names is flexible
myFunc[MAX=906, COLOR=blue fs]
myFunc[MAX=906, COLOR=blue fs]

NB. Order of names is flexible
NB. Order of names is flexible
myFunc[COLOR=blue, MAX=906 fs]
myFunc[COLOR=blue, MAX=906 fs]
NB. Even the delimiters are flexible...
NB. Even the delimiters are flexible...
myFunc<MAX=906, COLOR=blue fs>
myFunc<MAX=906, COLOR=blue fs></lang>


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 498: Line 497:
'EXTRA', 'POSITIONAL', 'ARGUMENTS')
'EXTRA', 'POSITIONAL', 'ARGUMENTS')
SyntaxError: non-keyword arg after keyword arg
SyntaxError: non-keyword arg after keyword arg
>>> </lang>
>>></lang>


=={{header|Ruby}}==
=={{header|Ruby}}==

Revision as of 13:04, 21 November 2009

Task
Named parameters
You are encouraged to solve this task according to the task description, using any language you may know.

Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.

See also:

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. <lang Ada>procedure Foo (Arg_1 : Integer; Arg_2 : Float := 0.0);</lang> It can be equivalently called as: <lang Ada>Foo (1, 0.0); Foo (1); Foo (Arg_2 => 0.0, Arg_1 => 1); Foo (Arg_1 => 1);</lang>

AutoHotkey

AutoHotkey doesn't have named parameters, but they can be simulated as follows. ahk discussion <lang AutoHotkey>MyFunc( "Val=0, w=1024, Text=The Quick Brown Fox, newVar=I'm New" )

MyFunc( _overrides="" ) {

Static x=5, y=5, w=100, h=100, Count
Name:="AutoHotkey", Type:="Scripting", Text:="qwerty", Val:=True

Loop, Parse, _overrides,`,=, %A_Space%  ; Override routine for Local/Static variables
  A_Index & 1  ? (_:=A_LoopField) : (%_%:=A_LoopField)
  

Listvars

WinWaitClose, %A_ScriptFullPath%

}</lang>

Common Lisp

<lang lisp>(defun print-name (&key first (last "?"))

 (princ last)
 (when first
   (princ ", ")
   (princ first))
 (values))</lang>

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

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

In Common Lisp, the arguments to a function are always a simple list of values; the &key facility merely defines an interpretation of that list by the function: alternating keys and values. (As a result of this, mixing varargs (&rest) 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.)

E

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]) {

   if (last == null) {
       print("?")
   } else {
       print(last)
   }
   if (first != null) {
       print(", ")
       print(first)
   }

}</lang>

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

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

? printName(["last" => "Doe"]) Doe

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

Fortran

Works with: Fortran version 95 and later

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)

 integer, intent(in) :: arg1, arg2
 integer, intent(out), optional :: arg3
 ! ...

end subroutine a_sub</lang>

<lang fortran>! usage

 integer :: r
 call a_sub(1,2, r)
 call a_sub(arg2=2, arg1=1)</lang>

The presence of an optional argument can be tested with PRESENT; 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)

  integer, intent(in), optional :: arg1
  integer, intent(in) :: arg2
  !...

end subroutine b_sub</lang>

<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</lang>

J

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 calling convention J script, one could write:

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

NB. Commas, like other langs myFunc['c:\file.txt', 906, 'blue' fs]

NB. Unspecified args are defaulted ("optional") myFunc['c:\file.txt' fs]

NB. Can use named arguments, like eg VB myFunc[color='blue' fs]

NB. Often values needn't be quoted myFunc[color= blue fs]

NB. Combination of comma syntax and name=value myFunc[max=906, color=blue fs]

NB. Spelling of names is flexible myFunc[MAX=906, COLOR=blue fs]

NB. Order of names is flexible myFunc[COLOR=blue, MAX=906 fs]

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

For further discussion, see the corresponding thread in the J Forums.

JavaScript

JavaScript only has positional parameters, but named parameters can be emulated by passing an object with the appropriate properties: <lang javascript>function example(options)

 // assign some defaults where the user's has not provided a value
 opts = {}
 opts.foo = options.foo || 0;
 opts.bar = options.bar || 1;
 opts.grill = options.grill || 'pork chops'
 print("foo is " + opts.foo + ", bar is " + opts.bar + ", and grill is " + opts.grill);

end

example({grill: "lamb kebab", bar: 3.14}); // => "foo is 0, bar is 3.14, and grill is lamb kebab"</lang>

Modula-3

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> It can be equivalently called as: <lang modula3>Foo(1, 0.0); Foo(1); Foo(Arg2 := 0.0, Arg1 := 1); Foo(Arg1 := 1);</lang>

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.) <lang objc>@interface Demo : Object {

   // Omitted ...

}

- (double) hypotenuseOfX: (double)x andY: (double)y; - (double) hypotenuseOfX: (double)x andY: (double)y andZ: (double)z;

@end</lang> <lang objc>@implementation Demo

- (double) hypotenuseOfX: (double)x andY: (double)y {

   return hypot(x,y);

} - (double) hypotenuseOfX: (double)x andY: (double)y andZ: (double)z {

   return hypot(hypot(x, y), z);

}

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

OCaml

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;; val foo : arg1:int -> arg2:int -> int = <fun>

  1. let foo ~arg1:x ~arg2:y = x + y;; (* you can also use different variable names internally if you want *)

val foo : arg1:int -> arg2:int -> int = <fun>

  1. foo ~arg2:17 ~arg1:42;;

- : int = 59</lang>

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 curried. If you partially apply a function on a named argument (even if the named argument is not first in the function declaration), it will evaluate to a function of the remaining arguments.

Named arguments can be made optional, with the ?(arg = value) syntax in the parameter declaration. See the optional parameters task for more details.

Perl

Perl has no formal parameters. Instead, Perl subroutines access all of their arguments through the special array @_. You can easily implement named arguments by making your function interpret @_ (or part of it) as a hash.

<lang perl>sub funkshun

  {my %h = @_;
   # Print every argument and its value.
   print qq(Argument "$_" has value "$h{$_}".\n)
       foreach sort keys %h;
   # If a 'verbosity' argument was passed in, print its value,
   # whatever that value may be.
   exists $h{verbosity}
       and print "Verbosity specified as $h{verbosity}.\n";
   # Say that safe mode is on if 'safe' is set to a true value.
   # Otherwise, say that it's off.
   print "Safe mode ", ($h{safe} ? 'on' : 'off'), ".\n";}</lang>

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

   verbosity => 3, password => 'foobie blech',
   extra_lives => 3, '42' => 'answer', password => 'joshua';</lang>

Its output:

Argument "42" has value "answer".
Argument "extra_lives" has value "3".
Argument "password" has value "joshua".
Argument "verbosity" has value "3".
Verbosity specified as 3.
Safe mode off.

Perl 6

Works with: Rakudo version #22 "Thousand Oaks"

Perl 6's support for optional parameters is much like Python's. Consider this declaration:

<lang perl6>sub funkshun ($a, $b?, $c = 15, :$d, *@e, *%f) {

  ...

}</lang>

In the above signature:

  • $a is a mandatory parameter that can be passed by position (funkshun 15, ...) or by name (funkshun a => 15, ...).
  • $b is an optional parameter that can be passed by position or by name. By default, it's undefined.
  • $c is an optional parameter that can be passed by position or by name. Its default value is 15.
  • $d is an optional parameter that can only be passed by name. By default, it's undefined.
  • @e is a slurpy array: it receives any leftover positional arguments.
  • %f is a slurpy hash: it receives any leftover named arguments.

So, if we defined the function like this:

<lang perl6>sub funkshun ($a, $b?, $c = 15, :$d, *@e, *%f) {

  say "$a $b $c $d";
  say join ' ', @e;
  say join ' ', keys %f;

}</lang>

this particularly thorny call:

<lang perl6>funkshun

   'Alfa', k1 => 'v1', c => 'Charlie', 'Bravo', 'e1',
   d => 'Delta', 'e2', k2 => 'v2';</lang>

would print this:

Alfa Bravo Charlie Delta
e1 e2
k1 k2

PowerShell

Positional parameters

When writing a function and not stating any parameters explicitly, such as the following function <lang powershell>function Test {

   Write-Host Argument 1 is $args[0]

}</lang> the only option are positional parameters using the $args array.

Named parameters

Stating any number of parameters directly in the function definition, such as <lang powershell>function Test ($SomeArgument, $AnotherArgument, $ThirdArgument) {

   Write-Host "Some argument:    $SomeArgument"
   Write-Host "Another argument: $AnotherArgument"
   Write-Host "Third argument:   $ThirdArgument"

}</lang> 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:

PS> Test -ThirdArgument foo -AnotherArgument bar -SomeArgument baz
Some argument:    baz
Another argument: bar
Third argument:   foo

However, one can still just give the arguments in order without explicitly having to state the names of the parameters.

Arbitrary arguments can be omitted as well:

PS> Test -ThirdArgument foo -AnotherArgument bar
Some argument:
Another argument: bar
Third argument:   foo

This will cause the omitted arguments to have the value $null

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. <lang powershell>function SwitchTest ([switch] $on) {

   Write-Host Switched $(if ($on) { "on" } else { "off" })

}</lang> 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):

PS> SwitchTest
Switched off
PS> SwitchTest -on
Switched on

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 $null. This is not always the desired value, though. Default values can be given too: <lang powershell>function Greeting ($Name = "Nobody") {

   Write-Host Hello, $Name!

}</lang> If the Name argument is omitted now, its value will be "Nobody" instead of $null:

PS> Greeting
Hello Nobody!
PS> Greeting John
Hello John!

Python

Basic explanation

A more detailed explanation of parameters, arguments, and how they are used is in the sections below. This is a simplified explanation:

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):

   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</lang>

Parameters can be made optional by providing a default argument, as described in the optional parameters article.

Detailed Explanation

Function Definition Parameters

Function definitions in Python allow for the following parameter types:

  • Optional default parameter types which are explicitly specified by name, and may have an optional default value.
  • An optional positional parameter which is an identifier preceded by "*".
  • And an optional keyword parameter which is an identifier preceded by "**".

If any of the parameter types are given then they must appear in the order specified above.

The syntax of function parameter declarations is more formally defined as:

funcdef        ::=  "def" funcname "(" [parameter_list] ")" ":" suite
dotted_name    ::=  identifier ("." identifier)*
parameter_list ::=  (defparameter ",")*
                    (  posparameter [, keyparameter]
                    | keyparameter
                    | defparameter [","] )
defparameter   ::=  parameter ["=" expression]
posparameter   ::=  "*" identifier
keyparameter   ::=  "**" identifier
sublist        ::=  parameter ("," parameter)* [","]
parameter      ::=  identifier | "(" sublist ")"

Function Call Arguments

The call of a function in python can use the following argument types:

  • Positional arguments that are mapped by their position in the call argument list to the defparameter name in the corresponding position of the function definition.
  • Sequence arguments that are the character "*" followed by an expression evaluating to a sequence (such as a list or tuple). The values from the sequence are unpacked and mapped like individual positional arguments to defparameters of the function definition. Sequence arguments are “evaluated before any keyword argument, irrespecctive of their relative positions in an argument list”.
  • All positional arguments must appear before any keyword argument.
  • Keyword arguments of the form parameter_name "=" value will map the value to the defparameter in the definition of the same name.
  • Mapping arguments that are the characters "**" followed by an expression evaluating to a mapping (such as a dict/hash). The key, value pairs from the mapping are unpacked and mapped like individual keyword arguments to defparameters of the function definition.
  • If the function definition includes a positional parameter, then if the assignment of positional arguments and sequence arguments in the call gives more values than the defparameters of the definition, then these extra arguments are assembled, in order, into a tuple that is assigned to the posparameter of the definition.
  • If the function definition includes a keyword parameter, then if the parameter name of any keyword arguments and mapping arguments in the call is unknown in the defparameters of the function definition, then these extra keyword/value pairs are assembled into a dict that is assigned to the keyparameter of the definition.
  • Any default parameter of the function definition that is not assigned a value at this point, but which has a default value, will be aassigned this default value, without re-evaluating the default value.
  • Any default parameter of the function definition that is still un-assigned will cause a TypeError exception to be raised.
  • In addition, multiple mappings to any parameter will raise a TypeError exception. (This includes multiple mappings into a keyparameter or keyword arguments clashing with positional/sequence arguments).

The more formal definition of a function call's syntax is

call                 ::=  primary "(" [argument_list [","]
                          | expression genexpr_for] ")"
argument_list        ::=  positional_arguments ["," keyword_arguments]
                            ["," sequence_argument] ["," keyword_arguments]
                            ["," mapping_argument]
                          | keyword_arguments ["," sequence_argument]
                            ["," mapping_argument]
                          | sequence_argument ["," sequence_argument] ["," mapping_argument]
                          | mapping_argument
positional_arguments ::=  expression ("," expression)*
keyword_arguments    ::=  keyword_item ("," keyword_item)*
sequence_argument    ::=  "*" expression
mapping_argument     ::=  "**" expression
keyword_item         ::=  identifier "=" expression

Examples

<lang python>>>> from __future__ import print_function >>> >>> def show_args(defparam1, defparam2 = 'default value', *posparam, **keyparam):

 "Straight-forward function to show its arguments"
 print ("  Default Parameters:")
 print ("    defparam1 value is:", defparam1)
 print ("    defparam2 value is:", defparam2)
 print ("  Positional Arguments:")
 if posparam:
   n = 0
   for p in posparam:
     print ("    positional argument:", n, "is:", p)
     n += 1
 else:
   print ("    <None>")
 print ("  Keyword Arguments (by sorted key name):")
 if keyparam:
   for k,v in sorted(keyparam.items()):
     print ("    keyword argument:", k, "is:", v)
 else:
   print ("    <None>")


>>> show_args('POSITIONAL', 'ARGUMENTS')

 Default Parameters:
   defparam1 value is: POSITIONAL
   defparam2 value is: ARGUMENTS
 Positional Arguments:
   <None>
 Keyword Arguments (by sorted key name):
   <None>

>>> show_args(defparam2='ARGUMENT', defparam1='KEYWORD')

 Default Parameters:
   defparam1 value is: KEYWORD
   defparam2 value is: ARGUMENT
 Positional Arguments:
   <None>
 Keyword Arguments (by sorted key name):
   <None>

>>> show_args( *('SEQUENCE', 'ARGUMENTS') )

 Default Parameters:
   defparam1 value is: SEQUENCE
   defparam2 value is: ARGUMENTS
 Positional Arguments:
   <None>
 Keyword Arguments (by sorted key name):
   <None>

>>> show_args( **{'defparam2':'ARGUMENTS', 'defparam1':'MAPPING'} )

 Default Parameters:
   defparam1 value is: MAPPING
   defparam2 value is: ARGUMENTS
 Positional Arguments:
   <None>
 Keyword Arguments (by sorted key name):
   <None>

>>> show_args('ONLY DEFINE defparam1 ARGUMENT')

 Default Parameters:
   defparam1 value is: ONLY DEFINE defparam1 ARGUMENT
   defparam2 value is: default value
 Positional Arguments:
   <None>
 Keyword Arguments (by sorted key name):
   <None>

>>> show_args('POSITIONAL', 'ARGUMENTS',

             'EXTRA', 'POSITIONAL', 'ARGUMENTS')
 Default Parameters:
   defparam1 value is: POSITIONAL
   defparam2 value is: ARGUMENTS
 Positional Arguments:
   positional argument: 0 is: EXTRA
   positional argument: 1 is: POSITIONAL
   positional argument: 2 is: ARGUMENTS
 Keyword Arguments (by sorted key name):
   <None>

>>> show_args('POSITIONAL', 'ARGUMENTS',

             kwa1='EXTRA', kwa2='KEYWORD', kwa3='ARGUMENTS')
 Default Parameters:
   defparam1 value is: POSITIONAL
   defparam2 value is: ARGUMENTS
 Positional Arguments:
   <None>
 Keyword Arguments (by sorted key name):
   keyword argument: kwa1 is: EXTRA
   keyword argument: kwa2 is: KEYWORD
   keyword argument: kwa3 is: ARGUMENTS

>>> show_args('POSITIONAL',

             'ARGUMENTS', 'EXTRA', 'POSITIONAL', 'ARGUMENTS', 
             kwa1='EXTRA', kwa2='KEYWORD', kwa3='ARGUMENTS')
 Default Parameters:
   defparam1 value is: POSITIONAL
   defparam2 value is: ARGUMENTS
 Positional Arguments:
   positional argument: 0 is: EXTRA
   positional argument: 1 is: POSITIONAL
   positional argument: 2 is: ARGUMENTS
 Keyword Arguments (by sorted key name):
   keyword argument: kwa1 is: EXTRA
   keyword argument: kwa2 is: KEYWORD
   keyword argument: kwa3 is: ARGUMENTS

>>> # But note: >>> show_args('POSITIONAL', 'ARGUMENTS',

             kwa1='EXTRA', kwa2='KEYWORD', kwa3='ARGUMENTS', 
             'EXTRA', 'POSITIONAL', 'ARGUMENTS')

SyntaxError: non-keyword arg after keyword arg >>></lang>

Ruby

As with Tcl, Ruby has no direct support for named parameters, but the effect can be faked by passing hash name/value pairs: <lang ruby>def example(options)

 # assign some defaults, then apply the user's options
 opts = {:foo => 0, :bar => 1, :grill => "pork chops"}.merge(options)
 puts "foo is #{opts[:foo]}, bar is #{opts[:bar]}, and grill is #{opts[:grill]}"

end

  1. Note that -foo is omitted and -grill precedes -bar

example(:grill => "lamb kebab", :bar => 3.14)

  1. => "foo is 0, bar is 3.14, and grill is lamb kebab"</lang>

Smalltalk

As for Objective-C the methods signature is made of "Symbol:[OtherSymbol:]*" (* stands for 0 or more repetition of the part in the brackets), without the possibility to reorder them (it would be another signature) or to make them optional.

Works with: GNU Smalltalk

<lang smalltalk>Object subclass: AnotherClass [

  "..."
  initWithArray: anArray [ "single argument" ]
  initWithArray: anArray andString: aString [ 
       "two args; these two methods in usage resemble
        a named argument, with optional andString argument"
  ]
  "..."

]</lang>

Tcl

The simplest way of passing named parameters is to use the Tcl language's strong support for variadic commands together with its arrays. By convention (originally from Tk) the named parameters names start with a hyphen (“-”) and are called options. <lang tcl>proc example args {

   # Set the defaults
   array set opts {-foo 0 -bar 1 -grill "hamburger"}
   # Merge in the values from the caller
   array set opts $args
   # Use the arguments
   return "foo is $opts(-foo), bar is $opts(-bar), and grill is $opts(-grill)"

}

  1. Note that -foo is omitted and -grill precedes -bar

example -grill "lamb kebab" -bar 3.14

  1. => ‘foo is 0, bar is 3.14, and grill is lamb kebab’</lang>

More complex option parsing is possible, e.g., with the opt 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 -help option: <lang tcl>package require opt tcl::OptProc example {

   {-foo   -int   0           "The number of foos"}
   {-bar   -float 1.0         "How much bar-ness"}
   {-grill -any   "hamburger" "What to cook on the grill"}

} {

   return "foo is $foo, bar is $bar, and grill is $grill"

} example -grill "lamb kebab" -bar 3.14

  1. => ‘foo is 0, bar is 3.14, and grill is lamb kebab’

example -help

  1. Usage information:
  2. Var/FlagName Type Value Help
  3. ------------ ---- ----- ----
  4. ( -help gives this help )
  5. -foo int (0) The number of foos
  6. -bar float (1.0) How much bar-ness
  7. -grill any (hamburger) What to cook on the grill</lang>

Visual Basic

<lang vb>'the function Sub whatever(foo As Long, bar As Integer, baz As Byte, qux As String)

   '...

End Sub 'calling the function -- note the Pascal-style assignment operator Sub crap()

   whatever bar:=1, baz:=2, foo:=-1, qux:="Why is ev'rybody always pickin' on me?"

End Sub</lang>

XSLT

XSLT only allows specification of template parameters by name, not position. <lang xml><xsl:template name="table-header">

   <xsl:param name="title"/>
   ...

</xsl:template></lang>