Named parameters

From Rosetta Code
Revision as of 10:14, 29 June 2009 by rosettacode>ShinTakezou (smalltalk)
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:

Objective C

Objective C has a method call syntax that is visually identical to named arguments, but they are not optional and may not be reordered. (The effect may be simulated by declaring multiple functions with the same leading name part and arguments reordered.) <lang objc>@interface Demo : Object {

   // Omitted ...

} - (double) hypotenuseOfX: (double)x andY: (double)y; @end</lang> <lang objc>@implementation Demo

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

   return hypot(x,y);

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

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 the 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) but this is the most common way of doing it.