Named parameters

From Rosetta Code
Revision as of 09:14, 29 June 2009 by rosettacode>Dkf (Add an example in Obj-C)
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:”.

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.