Optional parameters: Difference between revisions

→‎{{header|Tcl}}: improve the satisfaction of the task by the examples
(added Ursala)
(→‎{{header|Tcl}}: improve the satisfaction of the task by the examples)
Line 404:
=={{header|Tcl}}==
 
Tcl supports optional parameters to procedures through two mechanisms. It can either work positionally (through giving default values for arguments) or by using a special last argument called “<code>args</code>” which will collect all the remaining arguments into a list that can be processed by the procedure.
In Tcl, optional arguments are collected when the last argument
to a proc definition is called "args". The ''lsort'' command has a similar API, but with different keywords, so we adapt them.
 
By convention,The optional positional parameter namesstyle inworks Tcllike start with a leading “this:<ttbr>-</tt>” character.
{{works with|Tcl|8.4}}
<lang Tcl>package require Tcl 8.5
puts<lang tcl>proc [tablesort $data{table -{ordering ""} {column 0} -{reverse 1]0}} {
set direction [expr {$reverse ? "-decreasing" : "-increasing"}]
if {$ordering ne ""} {
lsort -command $ordering $direction -index $column $table
} else {
lsort $direction -index $column $table
}
}
 
puts [tablesort $data -column 0]
puts [tablesort $data -ordering"" {1]
puts [tablesort $data "" 0 1]
puts [tablesort $data {
apply {{a b} {expr {[string length $a]-[string length $b]}}}
}]</lang>
 
When using the second style, it is often common to use [[Named Arguments]] (and in fact the “<code>lsort</code>” already works very much like this). Note that it is most common to use named arguments that start with a “<code>-</code>”, but we omit them here so that we formally match the requirements of the task.
<br>
{{works with|Tcl|8.5}}
<lang Tcl>package require Tcl 8.5; # Only for the list expansion syntax
 
proc tablesort {table args} {
array set opt {-ordering "" -column 0 -reverse 0}
array set opt $args
set pars [list -index $opt(-column)]
if {$opt(-reverse)} {lappend pars -decreasing}
if {$opt(-ordering) ne ""} {lappend pars -command $opt(-ordering)}
lsort {*}$pars $table
}
 
puts [tablesort $data]
puts [tablesort $data column 1]
# --> {"" q z} {a b c} {zap zip Zot}
puts [tablesort $data column 0]
 
puts [tablesort $data -column 0 reverse 1]
puts [tablesort $data ordering {
# --> {a b c} {"" q z} {zap zip Zot}
 
puts [tablesort $data -column 0]
# --> {"" q z} {a b c} {zap zip Zot}
 
puts [tablesort $data -column 0 -reverse 1]
# --> {zap zip Zot} {a b c} {"" q z}
 
puts [tablesort $data -ordering {
apply {{a b} {expr {[string length $b]-[string length $a]}}}
}]</lang>
# --> {zap zip Zot} {a b c} {"" q z}</lang>
 
=={{header|Ursala}}==
Anonymous user