Named parameters

From Rosetta Code
Revision as of 23:05, 28 June 2009 by rosettacode>Dkf (New task on named arguments (as opposed to positional ones))
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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.

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.