Optional parameters: Difference between revisions

Content added Content deleted
(→‎{{header|6502 Assembly}}: misunderstood the task so I removed the entry)
m (syntax highlighting fixup automation)
Line 28: Line 28:
As described in [[Named_parameters]], all parameters have to be named. You can use positional or keyed association. Optional parameters are the ones with default values.
As described in [[Named_parameters]], all parameters have to be named. You can use positional or keyed association. Optional parameters are the ones with default values.


<lang Ada>package Tables is
<syntaxhighlight lang="ada">package Tables is


type Table is private;
type Table is private;
Line 41: Line 41:
private
private
... -- implementation specific
... -- implementation specific
end Tables;</lang>
end Tables;</syntaxhighlight>


example of use:
example of use:
<lang Ada>with Tables;
<syntaxhighlight lang="ada">with Tables;
procedure Table_Test is
procedure Table_Test is
My_Table : Tables.Table;
My_Table : Tables.Table;
Line 53: Line 53:
Sort (It => My_Table, Reverse_Ordering => True); -- use default sorting in reverse order
Sort (It => My_Table, Reverse_Ordering => True); -- use default sorting in reverse order
... -- other stuff
... -- other stuff
end Table_Test;</lang>
end Table_Test;</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68># as the options have distinct types (INT, BOOL and PROC( STRING, STRING )INT) the #
<syntaxhighlight lang="algol68"># as the options have distinct types (INT, BOOL and PROC( STRING, STRING )INT) the #
# easiest way to support these optional parameters in Algol 68 would be to have an array #
# easiest way to support these optional parameters in Algol 68 would be to have an array #
# with elements of these types #
# with elements of these types #
Line 90: Line 90:
configurable sort( data, ( 2, ( STRING a, STRING b )INT: default compare( a[ LWB a + 1 : ], b[ LWB b + 1 : ] ) ) );
configurable sort( data, ( 2, ( STRING a, STRING b )INT: default compare( a[ LWB a + 1 : ], b[ LWB b + 1 : ] ) ) );
# default sort #
# default sort #
configurable sort( data, () )</lang>
configurable sort( data, () )</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
AppleScript supports named, positional & prepositional parameters, but not default or optional parameters. Though that behavior can be simulated by passing lists or records as the parameter. Handler/functions can be passed as a parameter if they are part of a script object. AppleScript does not have built-in sorting functionality.
AppleScript supports named, positional & prepositional parameters, but not default or optional parameters. Though that behavior can be simulated by passing lists or records as the parameter. Handler/functions can be passed as a parameter if they are part of a script object. AppleScript does not have built-in sorting functionality.
<lang AppleScript>on sortTable(x)
<syntaxhighlight lang="applescript">on sortTable(x)
set {sortOrdering, sortColumn, sortReverse} to {sort_lexicographic, 1, false}
set {sortOrdering, sortColumn, sortReverse} to {sort_lexicographic, 1, false}
try
try
Line 113: Line 113:
return table
return table
end sort
end sort
end script</lang>
end script</syntaxhighlight>
Examples of use:
Examples of use:
<lang AppleScript>-- Another sort function.
<syntaxhighlight lang="applescript">-- Another sort function.
script sort_colex
script sort_colex
on sort(table, column, reverse)
on sort(table, column, reverse)
Line 129: Line 129:
sortTable({sequence:table, ordering:sort_colex, column:2, reverse:true})
sortTable({sequence:table, ordering:sort_colex, column:2, reverse:true})
sortTable({sequence:table, reverse:true})
sortTable({sequence:table, reverse:true})
sortTable({sequence:table})</lang>
sortTable({sequence:table})</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>sortTable: function [tbl][
<syntaxhighlight lang="rebol">sortTable: function [tbl][
column: "0"
column: "0"
reversed?: false
reversed?: false
Line 165: Line 165:
printTable sortTable.column:1 lst "Sorting by column=1"
printTable sortTable.column:1 lst "Sorting by column=1"
printTable sortTable.reverse lst "Sorting, reversed"
printTable sortTable.reverse lst "Sorting, reversed"
printTable sortTable.reverse.column:1 lst "Sorting by column=1, reversed"</lang>
printTable sortTable.reverse.column:1 lst "Sorting by column=1, reversed"</syntaxhighlight>


{{out}}
{{out}}
Line 191: Line 191:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
built in support for table sorting is available through the standard Win32 listview.
built in support for table sorting is available through the standard Win32 listview.
<lang AutoHotkey>Gosub start ; create and show the gui
<syntaxhighlight lang="autohotkey">Gosub start ; create and show the gui
sort_table("Text", column := 2, reverse := 1) ; lexicographic sort
sort_table("Text", column := 2, reverse := 1) ; lexicographic sort
Sleep, 2000
Sleep, 2000
Line 223: Line 223:


GuiClose:
GuiClose:
ExitApp</lang>
ExitApp</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
Line 247: Line 247:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
BBC BASIC doesn't have optional parameters, but functions can have multiple entry points which take different numbers of parameters, avoiding the need to duplicate code or call a sub-function. Omitted parameters can be declared as LOCAL, which initialises them to zero/false.
BBC BASIC doesn't have optional parameters, but functions can have multiple entry points which take different numbers of parameters, avoiding the need to duplicate code or call a sub-function. Omitted parameters can be declared as LOCAL, which initialises them to zero/false.
<lang bbcbasic> DIM table$(100,100)
<syntaxhighlight lang="bbcbasic"> DIM table$(100,100)
PROCsort_default(table$())
PROCsort_default(table$())
PROCsort_options(table$(), TRUE, 1, FALSE)
PROCsort_options(table$(), TRUE, 1, FALSE)
Line 256: Line 256:
REM The sort goes here, controlled by the options
REM The sort goes here, controlled by the options
REM Zero/FALSE values for the options shall select the defaults
REM Zero/FALSE values for the options shall select the defaults
ENDPROC</lang>
ENDPROC</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
Bracmat functions always have exactly one parameter, which is references by <code>!arg</code> in the function body. Positional and (optional) named 'parameters' are retrieved from this single parameter <code>!arg</code> by pattern matching. It is a good custom to separate positional parameters by commas or periods and to separate the named parameters by spaces.
Bracmat functions always have exactly one parameter, which is references by <code>!arg</code> in the function body. Positional and (optional) named 'parameters' are retrieved from this single parameter <code>!arg</code> by pattern matching. It is a good custom to separate positional parameters by commas or periods and to separate the named parameters by spaces.
<lang bracmat>( ( sortTable
<syntaxhighlight lang="bracmat">( ( sortTable
= table ordering column reverse
= table ordering column reverse
. !arg
. !arg
Line 281: Line 281:
: ?table
: ?table
& sortTable$(!table.(column.2) (reverse.yes))
& sortTable$(!table.(column.2) (reverse.yes))
);</lang>
);</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>
#include <stdarg.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdio.h>
Line 450: Line 450:
printTable(&table, stdout, colFmts);
printTable(&table, stdout, colFmts);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
This implementation only accepts function pointers for the comparators, and does not accept function objects, for simplicity.
This implementation only accepts function pointers for the comparators, and does not accept function objects, for simplicity.
<lang cpp>#include <vector>
<syntaxhighlight lang="cpp">#include <vector>
#include <algorithm>
#include <algorithm>
#include <string>
#include <string>
Line 544: Line 544:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
There is a built-in sort routine, but rather than figure out what all these arguments are supposed to mean, I've just defined the interface.
There is a built-in sort routine, but rather than figure out what all these arguments are supposed to mean, I've just defined the interface.


<lang Clojure>(defn sort [table & {:keys [ordering column reverse?]
<syntaxhighlight lang="clojure">(defn sort [table & {:keys [ordering column reverse?]
:or {ordering :lex, column 1}}]
:or {ordering :lex, column 1}}]
(println table ordering column reverse?))
(println table ordering column reverse?))


(sort [1 8 3] :reverse? true)
(sort [1 8 3] :reverse? true)
[1 8 3] :lex 1 true</lang>
[1 8 3] :lex 1 true</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 560: Line 560:
Common Lisp has both named and positional parameters. The following example shows optional named parameters, using the <code>&key</code> keyword. Optional positional parameters are specified using the <code>&optional</code> keyword.
Common Lisp has both named and positional parameters. The following example shows optional named parameters, using the <code>&key</code> keyword. Optional positional parameters are specified using the <code>&optional</code> keyword.


<lang lisp>(defun sort-table (table &key (ordering #'string<)
<syntaxhighlight lang="lisp">(defun sort-table (table &key (ordering #'string<)
(column 0)
(column 0)
reverse)
reverse)
Line 566: Line 566:
(complement ordering)
(complement ordering)
ordering)
ordering)
:key (lambda (row) (elt row column))))</lang>
:key (lambda (row) (elt row column))))</syntaxhighlight>


(Notes: The builtin [http://www.lispworks.com/documentation/HyperSpec/Body/f_sort_.htm sort] takes a "less than" predicate function. The [http://www.lispworks.com/documentation/HyperSpec/Body/f_comple.htm complement] function inverts a predicate.)
(Notes: The builtin [http://www.lispworks.com/documentation/HyperSpec/Body/f_sort_.htm sort] takes a "less than" predicate function. The [http://www.lispworks.com/documentation/HyperSpec/Body/f_comple.htm complement] function inverts a predicate.)


Example uses:
Example uses:
<lang lisp>CL-USER> (defparameter *data* '(("a" "b" "c") ("" "q" "z") ("zap" "zip" "Zot")))
<syntaxhighlight lang="lisp">CL-USER> (defparameter *data* '(("a" "b" "c") ("" "q" "z") ("zap" "zip" "Zot")))
*DATA*
*DATA*


Line 587: Line 587:


CL-USER> (sort-table *data* :ordering (lambda (a b) (> (length a) (length b))))
CL-USER> (sort-table *data* :ordering (lambda (a b) (> (length a) (length b))))
(("zap" "zip" "Zot") ("a" "b" "c") ("" "q" "z"))</lang>
(("zap" "zip" "Zot") ("a" "b" "c") ("" "q" "z"))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
{{trans|Python}}
{{trans|Python}}
<lang d>import std.stdio, std.algorithm, std.functional;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.functional;


string[][] sortTable(string[][] table,
string[][] sortTable(string[][] table,
Line 618: Line 618:
show(sortTable(data, null, 1, true));
show(sortTable(data, null, 1, true));
show(sortTable(data, (a,b) => b.length > a.length));
show(sortTable(data, (a,b) => b.length > a.length));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>["a", "b", "c"]
<pre>["a", "b", "c"]
Line 648: Line 648:
{{libheader| System.SysUtils}}
{{libheader| System.SysUtils}}
{{Trans|D}}
{{Trans|D}}
<lang Delphi>program Optional_parameters;
<syntaxhighlight lang="delphi">program Optional_parameters;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 813: Line 813:
end).ToString, #10);
end).ToString, #10);
Readln;
Readln;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 848: Line 848:
In E, as in Java and Smalltalk, optional parameters are defined as different methods with the same base name. Methods are distinguished by name (''verb'') and number of parameters (''arity'').
In E, as in Java and Smalltalk, optional parameters are defined as different methods with the same base name. Methods are distinguished by name (''verb'') and number of parameters (''arity'').


<lang e>def defaultOrdering(a, b) { return a.op__cmp(b) }
<syntaxhighlight lang="e">def defaultOrdering(a, b) { return a.op__cmp(b) }


def sort {
def sort {
Line 869: Line 869:
}
}


}</lang>
}</syntaxhighlight>


Named parameters are not builtin, but map-patterns may be used as a substitute. (TODO: Example of this) [[Category:E examples needing attention]]
Named parameters are not builtin, but map-patterns may be used as a substitute. (TODO: Example of this) [[Category:E examples needing attention]]
Line 875: Line 875:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang elixir>defmodule Optional_parameters do
<syntaxhighlight lang="elixir">defmodule Optional_parameters do
def sort( table, options\\[] ) do
def sort( table, options\\[] ) do
options = options ++ [ ordering: :lexicographic, column: 0, reverse: false ]
options = options ++ [ ordering: :lexicographic, column: 0, reverse: false ]
Line 905: Line 905:
end
end


Optional_parameters.task</lang>
Optional_parameters.task</syntaxhighlight>


{{out}}
{{out}}
Line 918: Line 918:


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( optional_parameters ).
-module( optional_parameters ).


Line 958: Line 958:
table_row2() -> {"456", "0789", "123"}.
table_row2() -> {"456", "0789", "123"}.
table_row3() -> {"0789", "123", "456"}.
table_row3() -> {"0789", "123", "456"}.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 979: Line 979:
Typically, parameters are named at the caller site when optional parameters are involved. However, this is not technically required as long as only right-most arguments are omitted.
Typically, parameters are named at the caller site when optional parameters are involved. However, this is not technically required as long as only right-most arguments are omitted.


<lang fsharp>type Table(rows:string[][]) =
<syntaxhighlight lang="fsharp">type Table(rows:string[][]) =
// in-place sorting of rows
// in-place sorting of rows
member x.Sort(?ordering, ?column, ?reverse) =
member x.Sort(?ordering, ?column, ?reverse) =
Line 1,015: Line 1,015:


t.Sort(ordering=fun s1 s2 -> compare s2.Length s1.Length)
t.Sort(ordering=fun s1 s2 -> compare s2.Length s1.Length)
printfn "Sorted by decreasing length"; t.Print()</lang>
printfn "Sorted by decreasing length"; t.Print()</syntaxhighlight>


Output:
Output:
Line 1,045: Line 1,045:
=={{header|Factor}}==
=={{header|Factor}}==
Factor doesn't have special support for optional parameters, so the idiom is to define a tuple with desired initial values, set the desired slots, then pass it to a word.
Factor doesn't have special support for optional parameters, so the idiom is to define a tuple with desired initial values, set the desired slots, then pass it to a word.
<lang factor>USING: accessors combinators io kernel math.order prettyprint
<syntaxhighlight lang="factor">USING: accessors combinators io kernel math.order prettyprint
sequences sorting ;
sequences sorting ;


Line 1,102: Line 1,102:
t >>reversed?
t >>reversed?
[ length ] >>ordering
[ length ] >>ordering
sort-table simple-table.</lang>
sort-table simple-table.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,136: Line 1,136:
In Fortran, each argument has its "name". The <tt>optional</tt> attribute can be used to specify that an argument is optional, and its presence (or absence) can be tested using the <tt>present</tt> intrinsic (so that we can give a default value, or execute accordingly a totally different code).
In Fortran, each argument has its "name". The <tt>optional</tt> attribute can be used to specify that an argument is optional, and its presence (or absence) can be tested using the <tt>present</tt> intrinsic (so that we can give a default value, or execute accordingly a totally different code).


<lang fortran>module ExampleOptionalParameter
<syntaxhighlight lang="fortran">module ExampleOptionalParameter
! use any module needed for the sort function(s)
! use any module needed for the sort function(s)
! and all the interfaces needed to make the code work
! and all the interfaces needed to make the code work
Line 1,204: Line 1,204:
end subroutine sort_table
end subroutine sort_table


end module ExampleOptionalParameter</lang>
end module ExampleOptionalParameter</syntaxhighlight>


<lang fortran>program UsingTest
<syntaxhighlight lang="fortran">program UsingTest
use ExampleOptionalParameter
use ExampleOptionalParameter
implicit none
implicit none
Line 1,241: Line 1,241:
call sort_table(table, column=2)
call sort_table(table, column=2)


end program UsingTest</lang>
end program UsingTest</syntaxhighlight>




=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>Function power(n As Integer, p As Integer = 2) As Double
<syntaxhighlight lang="freebasic">Function power(n As Integer, p As Integer = 2) As Double
Return n ^ p
Return n ^ p
End Function
End Function
Line 1,251: Line 1,251:
Print power(2) ' muestra 4
Print power(2) ' muestra 4
Print power(2, 3) ' muestra 8
Print power(2, 3) ' muestra 8
Sleep</lang>
Sleep</syntaxhighlight>




Line 1,269: Line 1,269:
Here is a partial example, partial because it doesn't really have the feel yet of "optional parameters." Note the call to do the reverse sort takes three lines of code, one to construct the parameter struct, one to set the option, and one more to make the call.
Here is a partial example, partial because it doesn't really have the feel yet of "optional parameters." Note the call to do the reverse sort takes three lines of code, one to construct the parameter struct, one to set the option, and one more to make the call.


<lang go>type cell string
<syntaxhighlight lang="go">type cell string


type spec struct {
type spec struct {
Line 1,288: Line 1,288:
s := newSpec
s := newSpec
s.reverse = true
s.reverse = true
t.sort(s)</lang>
t.sort(s)</syntaxhighlight>


===Struct literal with keyed elements===
===Struct literal with keyed elements===
Line 1,294: Line 1,294:
A solution providing more the feel of optional parameters is to pass a struct literal. Go allows a
A solution providing more the feel of optional parameters is to pass a struct literal. Go allows a
struct literal to be initialized with named fields but does not require all fields to be specified and does not require them to be specified in order. Thus passing a struct literal can provide very much the feel of optional named parameters. Given,
struct literal to be initialized with named fields but does not require all fields to be specified and does not require them to be specified in order. Thus passing a struct literal can provide very much the feel of optional named parameters. Given,
<lang go>type spec struct {
<syntaxhighlight lang="go">type spec struct {
ordering func(cell, cell) bool
ordering func(cell, cell) bool
column int
column int
reverse bool
reverse bool
}</lang>
}</syntaxhighlight>
the following struct literal fills in zero values for ordering and column and assigns true to the field reverse.
the following struct literal fills in zero values for ordering and column and assigns true to the field reverse.
<lang go>spec{reverse: true}</lang>
<syntaxhighlight lang="go">spec{reverse: true}</syntaxhighlight>
Structs in Go are values and are copied when passed as parameters. The result of having a single struct parameter is that the three fields are pushed on the stack, just about like they would if they were separate parameters. The effect is named parameters with unmentioned parameters defaulting to their zero value.
Structs in Go are values and are copied when passed as parameters. The result of having a single struct parameter is that the three fields are pushed on the stack, just about like they would if they were separate parameters. The effect is named parameters with unmentioned parameters defaulting to their zero value.


Line 1,306: Line 1,306:


Nevertheless, a complete program to demonstrate:
Nevertheless, a complete program to demonstrate:
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,398: Line 1,398:
})
})
t.printRows("sorted by descending string length on second column")
t.printRows("sorted by descending string length on second column")
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,433: Line 1,433:
A technique that gets a nod of approval from the idiom police is sometimes termed "functional options." This technique involves a bit of tricky machinery though and so has not really gained wide popularity. It makes use of Go's variadic arguments and uses functions to initialize a parameter struct. A full solution:
A technique that gets a nod of approval from the idiom police is sometimes termed "functional options." This technique involves a bit of tricky machinery though and so has not really gained wide popularity. It makes use of Go's variadic arguments and uses functions to initialize a parameter struct. A full solution:


<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,544: Line 1,544:
t.sort(column(1), ordering(byLen))
t.sort(column(1), ordering(byLen))
t.printRows("sorted by descending string length on second column")
t.printRows("sorted by descending string length on second column")
}</lang>
}</syntaxhighlight>
Output same as previous solution.
Output same as previous solution.


=={{header|Groovy}}==
=={{header|Groovy}}==
Optional Parameters:
Optional Parameters:
<lang groovy>def orderedSort(Collection table, column = 0, reverse = false, ordering = {x, y -> x <=> y } as Comparator) {
<syntaxhighlight lang="groovy">def orderedSort(Collection table, column = 0, reverse = false, ordering = {x, y -> x <=> y } as Comparator) {
table.sort(false) { x, y -> (reverse ? -1 : 1) * ordering.compare(x[column], y[column])}
table.sort(false) { x, y -> (reverse ? -1 : 1) * ordering.compare(x[column], y[column])}
}</lang>
}</syntaxhighlight>


Test code:
Test code:
<lang groovy>def table = [['a', 'b', 'c'], ['', 'q', 'z'], ['zap', 'zip', 'Zot']]
<syntaxhighlight lang="groovy">def table = [['a', 'b', 'c'], ['', 'q', 'z'], ['zap', 'zip', 'Zot']]


assert orderedSort(table) == [['', 'q', 'z'], ['a', 'b', 'c'], ['zap', 'zip', 'Zot']]
assert orderedSort(table) == [['', 'q', 'z'], ['a', 'b', 'c'], ['zap', 'zip', 'Zot']]
Line 1,560: Line 1,560:
assert orderedSort(table, 1) == [['a', 'b', 'c'], ['', 'q', 'z'], ['zap', 'zip', 'Zot']]
assert orderedSort(table, 1) == [['a', 'b', 'c'], ['', 'q', 'z'], ['zap', 'zip', 'Zot']]
assert orderedSort(table, 1, true) == [['zap', 'zip', 'Zot'],['', 'q', 'z'],['a', 'b', 'c']]
assert orderedSort(table, 1, true) == [['zap', 'zip', 'Zot'],['', 'q', 'z'],['a', 'b', 'c']]
assert orderedSort(table, 0, false, {x, y -> y?.size() <=> x?.size()} as Comparator) == [['zap', 'zip', 'Zot'],['a', 'b', 'c'],['', 'q', 'z']]</lang>
assert orderedSort(table, 0, false, {x, y -> y?.size() <=> x?.size()} as Comparator) == [['zap', 'zip', 'Zot'],['a', 'b', 'c'],['', 'q', 'z']]</syntaxhighlight>


Named Parameters:
Named Parameters:
<lang groovy>Collection.metaClass.orderedSort = { params ->
<syntaxhighlight lang="groovy">Collection.metaClass.orderedSort = { params ->
def column = params?.column ?: 0
def column = params?.column ?: 0
def reverse = params?.reverse ?: false
def reverse = params?.reverse ?: false
Line 1,569: Line 1,569:


table.sort(false) { x, y -> (reverse ? -1 : 1) * ordering.compare(x[column], y[column])}
table.sort(false) { x, y -> (reverse ? -1 : 1) * ordering.compare(x[column], y[column])}
}</lang>
}</syntaxhighlight>


Test Code:
Test Code:


<lang groovy>def table = [['a', 'b', 'c'], ['', 'q', 'z'], ['zap', 'zip', 'Zot']]
<syntaxhighlight lang="groovy">def table = [['a', 'b', 'c'], ['', 'q', 'z'], ['zap', 'zip', 'Zot']]


assert table.orderedSort() == [['', 'q', 'z'], ['a', 'b', 'c'], ['zap', 'zip', 'Zot']]
assert table.orderedSort() == [['', 'q', 'z'], ['a', 'b', 'c'], ['zap', 'zip', 'Zot']]
Line 1,579: Line 1,579:
assert table.orderedSort(column: 1) == [['a', 'b', 'c'], ['', 'q', 'z'], ['zap', 'zip', 'Zot']]
assert table.orderedSort(column: 1) == [['a', 'b', 'c'], ['', 'q', 'z'], ['zap', 'zip', 'Zot']]
assert table.orderedSort(column: 1, reverse: true) == [['zap', 'zip', 'Zot'],['', 'q', 'z'],['a', 'b', 'c']]
assert table.orderedSort(column: 1, reverse: true) == [['zap', 'zip', 'Zot'],['', 'q', 'z'],['a', 'b', 'c']]
assert table.orderedSort(ordering: {x, y -> y?.size() <=> x?.size()} as Comparator) == [['zap', 'zip', 'Zot'],['a', 'b', 'c'],['', 'q', 'z']]</lang>
assert table.orderedSort(ordering: {x, y -> y?.size() <=> x?.size()} as Comparator) == [['zap', 'zip', 'Zot'],['a', 'b', 'c'],['', 'q', 'z']]</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
Option 1: Using haskell's record update syntax, we can simulate named default arguments. This method has the drawback of not allowing for a parameter to be positional and named simultaneously.
Option 1: Using haskell's record update syntax, we can simulate named default arguments. This method has the drawback of not allowing for a parameter to be positional and named simultaneously.
<lang haskell>
<syntaxhighlight lang="haskell">
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE RecordWildCards #-}


Line 1,599: Line 1,599:
sorter defSortArgs [[]]
sorter defSortArgs [[]]
return ()
return ()
</syntaxhighlight>
</lang>


Option 2: This method has the drawback of being a bit verbose and requiring you to supply "Maybe a" arguments.
Option 2: This method has the drawback of being a bit verbose and requiring you to supply "Maybe a" arguments.
<lang haskell>
<syntaxhighlight lang="haskell">
import Data.Maybe (fromMaybe)
import Data.Maybe (fromMaybe)
-- Use fromMaybe as an operator because its prettier
-- Use fromMaybe as an operator because its prettier
Line 1,615: Line 1,615:
sorter (Just "foo") (Just 1) (Just True)
sorter (Just "foo") (Just 1) (Just True)
sorter Nothing Nothing Nothing
sorter Nothing Nothing Nothing
</syntaxhighlight>
</lang>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Optional named parameters are not the norm in Icon/Unicon. In the example below ''bubblesortf'' would be a version of [[Sorting_algorithms/Bubble_sort#Icon_and_Unicon|Bubble Sort]] modified to sort on a column number (Ordering is already supported). It could equally be replaced by any similarly modified Rosetta sort. The use of ''reverse'' on a list is a Unicon extension; in Icon a procedure from the IPL must be linked.
Optional named parameters are not the norm in Icon/Unicon. In the example below ''bubblesortf'' would be a version of [[Sorting_algorithms/Bubble_sort#Icon_and_Unicon|Bubble Sort]] modified to sort on a column number (Ordering is already supported). It could equally be replaced by any similarly modified Rosetta sort. The use of ''reverse'' on a list is a Unicon extension; in Icon a procedure from the IPL must be linked.
<lang Icon>
<syntaxhighlight lang="icon">
procedure main()
procedure main()
X := [ [1,2,3], [2,3,1], [3,1,2]) # A list of lists
X := [ [1,2,3], [2,3,1], [3,1,2]) # A list of lists
Line 1,639: Line 1,639:
}
}
return (\reverseorder|1)(bubblesortf(X,\c|1,\op|"<<")) # reverse or return the sorted list
return (\reverseorder|1)(bubblesortf(X,\c|1,\op|"<<")) # reverse or return the sorted list
end</lang>
end</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==


<lang j>srtbl=: verb define
<syntaxhighlight lang="j">srtbl=: verb define
'' srtbl y
'' srtbl y
:
:
'`ordering column reverse'=. x , (#x)}. ]`0:`0:
'`ordering column reverse'=. x , (#x)}. ]`0:`0:
|.^:reverse y /: ordering (column {"1 ])y
|.^:reverse y /: ordering (column {"1 ])y
)</lang>
)</syntaxhighlight>


For simplicity, the optional arguments are all functions, and are positional (on the left -- the table, with its arbitrary number of rows and columns, is on the right). Note also that the ordering function is expected to map its entire argument (since this offers much better efficiencies than a binary comparison).
For simplicity, the optional arguments are all functions, and are positional (on the left -- the table, with its arbitrary number of rows and columns, is on the right). Note also that the ordering function is expected to map its entire argument (since this offers much better efficiencies than a binary comparison).


'''Example Use'''
'''Example Use'''
<lang j> ]Table=: ('a';'b';'c'),('';'q';'z'),:'zip';'zap';'Zot'
<syntaxhighlight lang="j"> ]Table=: ('a';'b';'c'),('';'q';'z'),:'zip';'zap';'Zot'
┌───┬───┬───┐
┌───┬───┬───┐
│a │b │c │
│a │b │c │
Line 1,692: Line 1,692:
├───┼───┼───┤
├───┼───┼───┤
│zip│zap│Zot│
│zip│zap│Zot│
└───┴───┴───┘</lang>
└───┴───┴───┘</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
Line 1,698: Line 1,698:
Java has no optional parameters, but methods can be overloaded on the number and types of arguments, which can be used to effectively achieve optional positional parameters.
Java has no optional parameters, but methods can be overloaded on the number and types of arguments, which can be used to effectively achieve optional positional parameters.


<lang java>import java.util.*;
<syntaxhighlight lang="java">import java.util.*;


public class OptionalParams {
public class OptionalParams {
Line 1,770: Line 1,770:
// prints: [[zap, zip, Zot], [a, b, c], [, q, z]]
// prints: [[zap, zip, Zot], [a, b, c], [, q, z]]
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
See [[Named parameters#JavaScript]], to pass named parameters one uses an object with properties set:
See [[Named parameters#JavaScript]], to pass named parameters one uses an object with properties set:
<lang javascript>function sorter(table, options) {
<syntaxhighlight lang="javascript">function sorter(table, options) {
opts = {}
opts = {}
opts.ordering = options.ordering || 'lexicographic';
opts.ordering = options.ordering || 'lexicographic';
Line 1,783: Line 1,783:
}
}


sorter(the_data, {reverse: true, ordering: 'numeric'});</lang>
sorter(the_data, {reverse: true, ordering: 'numeric'});</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
Line 1,813: Line 1,813:
interpreted by jq. The key to understanding this is that jq functions
interpreted by jq. The key to understanding this is that jq functions
are compiled into closures. Here is an example:
are compiled into closures. Here is an example:
<lang jq>def bar: 2 *.;
<syntaxhighlight lang="jq">def bar: 2 *.;


def foo: {"a": bar};</lang>
def foo: {"a": bar};</syntaxhighlight>
The expression <tt>3 | foo.a</tt> evaluates to 6.
The expression <tt>3 | foo.a</tt> evaluates to 6.


Line 1,822: Line 1,822:
sort_table(ordering; column; reverse) is already defined. To specify the lexicographic
sort_table(ordering; column; reverse) is already defined. To specify the lexicographic
ordering on strings in terms of an arity-0 filter, we define less_than_or_equal/0 as follows:
ordering on strings in terms of an arity-0 filter, we define less_than_or_equal/0 as follows:
<lang jq>def less_than_or_equal: .[0] <= .[1];</lang>
<syntaxhighlight lang="jq">def less_than_or_equal: .[0] <= .[1];</syntaxhighlight>


'''The Task''':
'''The Task''':
<lang jq>def sorter(options):
<syntaxhighlight lang="jq">def sorter(options):
sort_table( if (options|has("ordering")) then options.ordering
sort_table( if (options|has("ordering")) then options.ordering
else less_than_or_equal
else less_than_or_equal
Line 1,833: Line 1,833:


# If jq > 1.4 is being used, we may also define:
# If jq > 1.4 is being used, we may also define:
def sorter: sorter({});</lang>
def sorter: sorter({});</syntaxhighlight>
'''Examples''':
'''Examples''':
<lang jq>[1,2] | sorter({ "reverse": true, "ordering": less_than_or_equal } )
<syntaxhighlight lang="jq">[1,2] | sorter({ "reverse": true, "ordering": less_than_or_equal } )


[1,2] | sorter({ "reverse": true })
[1,2] | sorter({ "reverse": true })


# If sorter/0 has also been defined:
# If sorter/0 has also been defined:
[1,2] | sorter</lang>
[1,2] | sorter</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
Julia supports both named and positional optional parameters. We can define both versions at the same time if we want:
Julia supports both named and positional optional parameters. We can define both versions at the same time if we want:
<lang julia>sorttable(T; ordering=<, column=1, reverse=false) =
<syntaxhighlight lang="julia">sorttable(T; ordering=<, column=1, reverse=false) =
sort(T, by = t -> t[column], lt = reverse ? (a,b) -> ordering(b,a) : ordering)
sort(T, by = t -> t[column], lt = reverse ? (a,b) -> ordering(b,a) : ordering)
sorttable(T, ordering=<, column=1, reverse=false) =
sorttable(T, ordering=<, column=1, reverse=false) =
sorttable(T, ordering=ordering, column=column, reverse=reverse)</lang>
sorttable(T, ordering=ordering, column=column, reverse=reverse)</syntaxhighlight>
where the <code>;</code> in the argument list denotes the named-parameter variant, and we have used Julia's built-in higher-order <code>sort</code> function to do the work. Note that we simply pass a comparison function for the ordering, and the built-in <code><</code> operator is actually just a function that (on strings) compares in lexicographic order.
where the <code>;</code> in the argument list denotes the named-parameter variant, and we have used Julia's built-in higher-order <code>sort</code> function to do the work. Note that we simply pass a comparison function for the ordering, and the built-in <code><</code> operator is actually just a function that (on strings) compares in lexicographic order.


Example output:
Example output:
<lang julia>julia> data = {["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]}
<syntaxhighlight lang="julia">julia> data = {["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]}
3-element Array{Any,1}:
3-element Array{Any,1}:
["a","b","c"]
["a","b","c"]
Line 1,867: Line 1,867:
["zap","zip","Zot"]
["zap","zip","Zot"]
["","q","z"]
["","q","z"]
["a","b","c"] </lang>
["a","b","c"] </syntaxhighlight>


=={{header|Klingphix}}==
=={{header|Klingphix}}==
<lang Klingphix>include ..\Utilitys.tlhy
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy


:mypower
:mypower
Line 1,884: Line 1,884:
"2 ^3 = " print ( 2 3 ) mypower ?
"2 ^3 = " print ( 2 3 ) mypower ?


"End " input</lang>
"End " input</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.51
<syntaxhighlight lang="scala">// version 1.1.51


typealias Table = List<List<String>>
typealias Table = List<List<String>>
Line 1,932: Line 1,932:
val table3 = table.sort(ordering = comp)
val table3 = table.sort(ordering = comp)
table3.print("Reverse case insensitive sort by col 2:")
table3.print("Reverse case insensitive sort by col 2:")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,979: Line 1,979:
=={{header|Lasso}}==
=={{header|Lasso}}==
Lasso can handle both positional and named params. Methods support multiple dispatch where each dispatch defines it's own set of parameters.
Lasso can handle both positional and named params. Methods support multiple dispatch where each dispatch defines it's own set of parameters.
<lang Lasso>define sortarray( // params are set by position
<syntaxhighlight lang="lasso">define sortarray( // params are set by position
items::array, // required param
items::array, // required param
ordering::string = 'lexicographic', // optional param
ordering::string = 'lexicographic', // optional param
Line 2,011: Line 2,011:
sortarray(-items = #items, -reverse)
sortarray(-items = #items, -reverse)


sortarray(#items)</lang>
sortarray(#items)</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
{{works with|UCB Logo}}
{{works with|UCB Logo}}
<lang logo>to sort :table [:column 1] [:ordering "before?] [:reverse "false]
<syntaxhighlight lang="logo">to sort :table [:column 1] [:ordering "before?] [:reverse "false]
; ...
; ...
end</lang>
end</syntaxhighlight>
The function "sort" has a default arity of 1 for the required parameter. When overriding default parameters, you must wrap the call in parentheses to specify the different arity.
The function "sort" has a default arity of 1 for the required parameter. When overriding default parameters, you must wrap the call in parentheses to specify the different arity.
<lang logo>sort :table
<syntaxhighlight lang="logo">sort :table
(sort :table 2)
(sort :table 2)
(sort :table 3 "less? "true)</lang>
(sort :table 3 "less? "true)</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<syntaxhighlight lang="lua">
<lang Lua>
function showTable(tbl)
function showTable(tbl)
if type(tbl)=='table' then
if type(tbl)=='table' then
Line 2,068: Line 2,068:
sortTable{table=A, cmp=(function (a, b) return #a < #b end)}
sortTable{table=A, cmp=(function (a, b) return #a < #b end)}
print('by length', showTable(A))
print('by length', showTable(A))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,080: Line 2,080:


=={{header|Maple}}==
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
OptionalSort := proc(input, {
OptionalSort := proc(input, {
ordering :: Or(procedures,identical("lexicographic")) := "lexicographic",
ordering :: Or(procedures,identical("lexicographic")) := "lexicographic",
Line 2,093: Line 2,093:
end if;
end if;
sort( input, compare );
sort( input, compare );
end proc:</lang>
end proc:</syntaxhighlight>


Some examples of this procedure in action:
Some examples of this procedure in action:
<syntaxhighlight lang="maple">
<lang Maple>
> L := [[1, 2], [3, 4], [-5, 7]]:
> L := [[1, 2], [3, 4], [-5, 7]]:
> OptionalSort(L);
> OptionalSort(L);
Line 2,104: Line 2,104:
> OptionalSort(L, reverse, column = 2);
> OptionalSort(L, reverse, column = 2);
[[-5, 7], [3, 4], [1, 2]]
[[-5, 7], [3, 4], [1, 2]]
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Options[OptionalSort]={ordering->lexicographic,column->1,reverse-> False};
<syntaxhighlight lang="mathematica">Options[OptionalSort]={ordering->lexicographic,column->1,reverse-> False};
OptionalSort[x_List,OptionsPattern[]]:=If[OptionValue[reverse]==True,
OptionalSort[x_List,OptionsPattern[]]:=If[OptionValue[reverse]==True,
SortBy[x ,#[[OptionValue[column]]]&]//Reverse,
SortBy[x ,#[[OptionValue[column]]]&]//Reverse,
Line 2,116: Line 2,116:


OptionalSort[{{"a" ,"b", "c"}, {"", "q", "z"},{"zap" ,"zip", "Zot"}},{ordering->lexicographic,column->2,reverse-> True} ]
OptionalSort[{{"a" ,"b", "c"}, {"", "q", "z"},{"zap" ,"zip", "Zot"}},{ordering->lexicographic,column->2,reverse-> True} ]
->{{zap,zip,Zot},{,q,z},{a,b,c}}</lang>
->{{zap,zip,Zot},{,q,z},{a,b,c}}</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
It's possible to use either optional parameters or overloading on parameter number (or type). However, it's less code repetition to use optional parameters when possible (unless, of course, the implementation varies drastically with different parameters).
It's possible to use either optional parameters or overloading on parameter number (or type). However, it's less code repetition to use optional parameters when possible (unless, of course, the implementation varies drastically with different parameters).
<lang Nemerle>Sorter (table : list[list[string]], ordering = "lexicographic", column = 0, reverse = false) : list[list[string]]
<syntaxhighlight lang="nemerle">Sorter (table : list[list[string]], ordering = "lexicographic", column = 0, reverse = false) : list[list[string]]
{
{
// implementation goes here
// implementation goes here
}</lang>
}</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import algorithm, strutils, sugar
<syntaxhighlight lang="nim">import algorithm, strutils, sugar


proc printTable(a: seq[seq[string]]) =
proc printTable(a: seq[seq[string]]) =
Line 2,147: Line 2,147:
printTable sortTable(data, column = 1)
printTable sortTable(data, column = 1)
printTable sortTable(data, column = 1, reverse = true)
printTable sortTable(data, column = 1, reverse = true)
printTable sortTable(data, ordering = (a,b) => cmp[int](b.len,a.len))</lang>
printTable sortTable(data, ordering = (a,b) => cmp[int](b.len,a.len))</syntaxhighlight>
Output:
Output:
<pre>a b c
<pre>a b c
Line 2,175: Line 2,175:
=={{header|Objective-C}}==
=={{header|Objective-C}}==
Without getting into any detail, here is one way you might implement optional arguments. (Note that since Objective-C is a strict superset of C, any C solution can be used as well.)
Without getting into any detail, here is one way you might implement optional arguments. (Note that since Objective-C is a strict superset of C, any C solution can be used as well.)
<lang objc>typedef enum { kOrdNone, kOrdLex, kOrdByAddress, kOrdNumeric } SortOrder;
<syntaxhighlight lang="objc">typedef enum { kOrdNone, kOrdLex, kOrdByAddress, kOrdNumeric } SortOrder;


@interface MyArray : NSObject {}
@interface MyArray : NSObject {}
Line 2,199: Line 2,199:
}
}


@end</lang>
@end</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
Line 2,205: Line 2,205:
OCaml has optional named parameters. It is conventional to place a non-optional parameter after the optional parameters, because if the optional parameters were at the end, then if you don't provide them, it will just look like a partial application (because OCaml supports [[currying]]), resulting in a function which still expects the optional parameters.
OCaml has optional named parameters. It is conventional to place a non-optional parameter after the optional parameters, because if the optional parameters were at the end, then if you don't provide them, it will just look like a partial application (because OCaml supports [[currying]]), resulting in a function which still expects the optional parameters.


<lang ocaml>let sort_table ?(ordering = compare) ?(column = 0) ?(reverse = false) table =
<syntaxhighlight lang="ocaml">let sort_table ?(ordering = compare) ?(column = 0) ?(reverse = false) table =
let cmp x y = ordering (List.nth x column) (List.nth y column) * (if reverse then -1 else 1) in
let cmp x y = ordering (List.nth x column) (List.nth y column) * (if reverse then -1 else 1) in
List.sort cmp table</lang>
List.sort cmp table</syntaxhighlight>


Example uses:
Example uses:
<lang ocaml># let data = [["a"; "b"; "c"]; [""; "q"; "z"]; ["zap"; "zip"; "Zot"]];;
<syntaxhighlight lang="ocaml"># let data = [["a"; "b"; "c"]; [""; "q"; "z"]; ["zap"; "zip"; "Zot"]];;
val data : string list list =
val data : string list list =
[["a"; "b"; "c"]; [""; "q"; "z"]; ["zap"; "zip"; "Zot"]]
[["a"; "b"; "c"]; [""; "q"; "z"]; ["zap"; "zip"; "Zot"]]
Line 2,227: Line 2,227:
# sort_table ~ordering:(fun a b -> compare (String.length b) (String.length a)) data;;
# sort_table ~ordering:(fun a b -> compare (String.length b) (String.length a)) data;;
- : string list list =
- : string list list =
[["zap"; "zip"; "Zot"]; ["a"; "b"; "c"]; [""; "q"; "z"]]</lang>
[["zap"; "zip"; "Zot"]; ["a"; "b"; "c"]; [""; "q"; "z"]]</syntaxhighlight>


OCaml does not support optional positional parameters, because, since OCaml supports currying, it would conflict with partial applications, where you do not provide all the arguments to a function, and it results in a function which expects the remaining arguments.
OCaml does not support optional positional parameters, because, since OCaml supports currying, it would conflict with partial applications, where you do not provide all the arguments to a function, and it results in a function which expects the remaining arguments.
Line 2,233: Line 2,233:
=={{header|Oz}}==
=={{header|Oz}}==
Oz supports optional parameters only for methods, not for functions.
Oz supports optional parameters only for methods, not for functions.
<lang oz>declare
<syntaxhighlight lang="oz">declare
class Table
class Table
attr
attr
Line 2,262: Line 2,262:
{T sort(column:2)}
{T sort(column:2)}
{T sort(column:2 reverse:true)}
{T sort(column:2 reverse:true)}
{T sort(ordering:fun {$ A B} {Length B} < {Length A} end)}</lang>
{T sort(ordering:fun {$ A B} {Length B} < {Length A} end)}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
As it happens the built-in <code>vecsort()</code> function fulfills all the requirements of this task. In general optional arguments are handled in GP by default values:
As it happens the built-in <code>vecsort()</code> function fulfills all the requirements of this task. In general optional arguments are handled in GP by default values:
<lang parigp>sort(v, ordering=0, column=0, reverse=0)</lang>
<syntaxhighlight lang="parigp">sort(v, ordering=0, column=0, reverse=0)</syntaxhighlight>
while in PARI it is handled by checking for NULL (assuming parser code DG, see 5.7.3 in the User's Guide to the PARI library):
while in PARI it is handled by checking for NULL (assuming parser code DG, see 5.7.3 in the User's Guide to the PARI library):
<syntaxhighlight lang="c">/*
<lang C>/*
GP;install("test_func", "vDG", "test", "path/to/test.gp.so");
GP;install("test_func", "vDG", "test", "path/to/test.gp.so");
*/
*/
Line 2,277: Line 2,277:
else
else
pari_printf("Argument was: %Ps\n", x);
pari_printf("Argument was: %Ps\n", x);
}</lang>
}</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
Line 2,284: Line 2,284:
This function expects its first argument to be a reference to an array of arrays. It interprets any remaining arguments as a hash of optional parameters.
This function expects its first argument to be a reference to an array of arrays. It interprets any remaining arguments as a hash of optional parameters.


<lang perl>sub sorttable
<syntaxhighlight lang="perl">sub sorttable
{my @table = @{shift()};
{my @table = @{shift()};
my %opt =
my %opt =
Line 2,293: Line 2,293:
{$func->($a->[$col], $b->[$col])}
{$func->($a->[$col], $b->[$col])}
@table;
@table;
return ($opt{reverse} ? [reverse @result] : \@result);}</lang>
return ($opt{reverse} ? [reverse @result] : \@result);}</syntaxhighlight>


An example of use:
An example of use:


<lang perl>my $a = [["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]];
<syntaxhighlight lang="perl">my $a = [["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]];
foreach (@{sorttable $a, column => 1, reverse => 1})
foreach (@{sorttable $a, column => 1, reverse => 1})
{foreach (@$_)
{foreach (@$_)
{printf "%-5s", $_;}
{printf "%-5s", $_;}
print "\n";}</lang>
print "\n";}</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
Line 2,307: Line 2,307:
Optional parameters are specified simply by declaring a default value. They must however be grouped on the right.
Optional parameters are specified simply by declaring a default value. They must however be grouped on the right.


<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">increment</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">inc</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">increment</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">inc</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">inc</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">inc</span>
Line 2,314: Line 2,314:
<span style="color: #0000FF;">?</span><span style="color: #000000;">increment</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- shows 6</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">increment</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- shows 6</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">increment</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- shows 7</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">increment</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- shows 7</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


You can also use a variable length sequence to emulate optional parameters.
You can also use a variable length sequence to emulate optional parameters.


<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d records sorted in %3.2s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">records</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d records sorted in %3.2s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">records</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


In other words printf always accepts exactly three arguments, but the third should contain the correct number of
In other words printf always accepts exactly three arguments, but the third should contain the correct number of
Line 2,327: Line 2,327:
The following incomplete snippet from demo\pGUI\listview.exw shows the basic idea for sorting a table by any column, up or down:
The following incomplete snippet from demo\pGUI\listview.exw shows the basic idea for sorting a table by any column, up or down:


<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #004080;">integer</span> <span style="color: #000000;">sortcol</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">sortcol</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">sortdir</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">sortdir</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
Line 2,349: Line 2,349:
<span style="color: #008080;">return</span> <span style="color: #000000;">data</span><span style="color: #0000FF;">[</span><span style="color: #000000;">l</span><span style="color: #0000FF;">][</span><span style="color: #000000;">c</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">data</span><span style="color: #0000FF;">[</span><span style="color: #000000;">l</span><span style="color: #0000FF;">][</span><span style="color: #000000;">c</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>def mypower
<syntaxhighlight lang="phixmonti">def mypower
1 tolist flatten len
1 tolist flatten len
1 == if
1 == if
Line 2,364: Line 2,364:


"2 ^2 = " print 2 mypower print nl
"2 ^2 = " print 2 mypower print nl
"2 ^3 = " print 2 3 2 tolist mypower print</lang>
"2 ^3 = " print 2 3 2 tolist mypower print</syntaxhighlight>
More elegant.
More elegant.
<lang Phixmonti>include ..\Utilitys.pmt
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt


def mypower
def mypower
Line 2,379: Line 2,379:


"2 ^2: " print 2 mypower ?
"2 ^2: " print 2 mypower ?
"2 ^3: " print ( 2 3 ) mypower ?</lang>
"2 ^3: " print ( 2 3 ) mypower ?</syntaxhighlight>
More in line with the task description
More in line with the task description
<lang Phixmonti>include ..\Utilitys.pmt
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt


( ( "a" "b" "c" )
( ( "a" "b" "c" )
Line 2,413: Line 2,413:
( 2 ) mysort pstack
( 2 ) mysort pstack
( 2 true ) mysort pstack
( 2 true ) mysort pstack
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,429: Line 2,429:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de sortTable (Tbl . @)
<syntaxhighlight lang="picolisp">(de sortTable (Tbl . @)
(let (Ordering prog Column 1 Reverse NIL) # Set defaults
(let (Ordering prog Column 1 Reverse NIL) # Set defaults
(bind (rest) # Bind optional params
(bind (rest) # Bind optional params
Line 2,436: Line 2,436:
sort
sort
Tbl ) )
Tbl ) )
(if Reverse (flip Tbl) Tbl) ) ) )</lang>
(if Reverse (flip Tbl) Tbl) ) ) )</syntaxhighlight>
Output:
Output:
<pre>(de *Data ("a" "bcdef" "X") (" " "qrst" "z") ("zap" "zip" "Zot"))
<pre>(de *Data ("a" "bcdef" "X") (" " "qrst" "z") ("zap" "zip" "Zot"))
Line 2,456: Line 2,456:


Using a pretty-printer for the table
Using a pretty-printer for the table
<lang python>>>> def printtable(data):
<syntaxhighlight lang="python">>>> def printtable(data):
for row in data:
for row in data:
print ' '.join('%-5s' % ('"%s"' % cell) for cell in row)
print ' '.join('%-5s' % ('"%s"' % cell) for cell in row)
Line 2,490: Line 2,490:
"a" "b" "c"
"a" "b" "c"
"" "q" "z"
"" "q" "z"
>>></lang>
>>></syntaxhighlight>


See the Python entry in [[Named_Arguments#Python|Named Arguments]] for a more comprehensive description of Python function parameters and call arguments.
See the Python entry in [[Named_Arguments#Python|Named Arguments]] for a more comprehensive description of Python function parameters and call arguments.
Line 2,510: Line 2,510:
=={{header|R}}==
=={{header|R}}==
Optional parameters are given using a name=value syntax within the function header.
Optional parameters are given using a name=value syntax within the function header.
<lang R>tablesort <- function(x, ordering="lexicographic", column=1, reverse=false)
<syntaxhighlight lang="r">tablesort <- function(x, ordering="lexicographic", column=1, reverse=false)
{
{
# Implementation
# Implementation
Line 2,516: Line 2,516:


# Usage is e.g.
# Usage is e.g.
tablesort(mytable, column=3)</lang>
tablesort(mytable, column=3)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 2,531: Line 2,531:
ordering)
ordering)
#:key (λ (row) (list-ref row column))))
#:key (λ (row) (list-ref row column))))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
Using named parameters:
Using named parameters:
<lang perl6>method sorttable(:$column = 0, :$reverse, :&ordering = &infix:<cmp>) {
<syntaxhighlight lang="raku" line>method sorttable(:$column = 0, :$reverse, :&ordering = &infix:<cmp>) {
my @result = self»[$column].sort: &ordering;
my @result = self»[$column].sort: &ordering;
return $reverse ?? @result.reverse !! @result;
return $reverse ?? @result.reverse !! @result;
}</lang>
}</syntaxhighlight>


Using optional positional parameters:
Using optional positional parameters:
<lang perl6>method sorttable-pos($column = 0, $reverse?, &ordering = &infix:<cmp>) {
<syntaxhighlight lang="raku" line>method sorttable-pos($column = 0, $reverse?, &ordering = &infix:<cmp>) {
my @result = self»[$column].sort: &ordering;
my @result = self»[$column].sort: &ordering;
return $reverse ?? @result.reverse !! @result;
return $reverse ?? @result.reverse !! @result;
}</lang>
}</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 2,551: Line 2,551:
<br>Also allowed are named parameters.
<br>Also allowed are named parameters.
<br><br>The REXX language doesn't have any native sorting functions, &nbsp; so you have to write your own sorting subroutine.
<br><br>The REXX language doesn't have any native sorting functions, &nbsp; so you have to write your own sorting subroutine.
<lang rexx>sortStrings: procedure expose @. /*the stemmed array is named: @. */
<syntaxhighlight lang="rexx">sortStrings: procedure expose @. /*the stemmed array is named: @. */
col= 1 /*set some defaults (here and below). */
col= 1 /*set some defaults (here and below). */
reverse= 'NO'
reverse= 'NO'
Line 2,573: Line 2,573:
... main body of string sort here ...
... main body of string sort here ...


return /*stick a fork in it, we're all done. */</lang>
return /*stick a fork in it, we're all done. */</syntaxhighlight>
An example use is:
An example use is:
<lang rexx>/*REXX example uses the SortStrings subroutine with some (passed) optional arguments. */
<syntaxhighlight lang="rexx">/*REXX example uses the SortStrings subroutine with some (passed) optional arguments. */




Line 2,582: Line 2,582:


call sortStrings 'Reverse=no' 3
call sortStrings 'Reverse=no' 3
/*stick a fork in it, we're all done. */</lang>
/*stick a fork in it, we're all done. */</syntaxhighlight>


=={{header|Ruby}}==
=={{header|Ruby}}==
Ruby allows default values for positional arguments, but they have disadvantages. In the next example, if you want to pass ''reverse=true'', you must also give values for ''ordering'' and ''column''.
Ruby allows default values for positional arguments, but they have disadvantages. In the next example, if you want to pass ''reverse=true'', you must also give values for ''ordering'' and ''column''.


<lang ruby>def table_sort(table, ordering=:<=>, column=0, reverse=false)
<syntaxhighlight lang="ruby">def table_sort(table, ordering=:<=>, column=0, reverse=false)
# ...</lang>
# ...</syntaxhighlight>


Ruby 2.0 added keyword arguments to the language. These provide the most natural solution.
Ruby 2.0 added keyword arguments to the language. These provide the most natural solution.


{{works with|Ruby|2.0}}
{{works with|Ruby|2.0}}
<lang ruby>def table_sort(table, ordering: :<=>, column: 0, reverse: false)
<syntaxhighlight lang="ruby">def table_sort(table, ordering: :<=>, column: 0, reverse: false)
p = ordering.to_proc
p = ordering.to_proc
if reverse
if reverse
Line 2,608: Line 2,608:
["Mexico City", "Mexico"],
["Mexico City", "Mexico"],
]
]
p table_sort(table, column: 1)</lang>
p table_sort(table, column: 1)</syntaxhighlight>


Older versions of Ruby can fake the effect with a Hash (as detailed in [[Named parameters#Ruby]]). The next example needs Ruby 1.8.7 only because the sort code calls <code>Symbol#to_proc</code>; the passing of parameters would yet work with Ruby older than 1.8.7.
Older versions of Ruby can fake the effect with a Hash (as detailed in [[Named parameters#Ruby]]). The next example needs Ruby 1.8.7 only because the sort code calls <code>Symbol#to_proc</code>; the passing of parameters would yet work with Ruby older than 1.8.7.


{{works with|Ruby|1.8.7}}
{{works with|Ruby|1.8.7}}
<lang ruby>def table_sort(table, opts = {})
<syntaxhighlight lang="ruby">def table_sort(table, opts = {})
defaults = {:ordering => :<=>, :column => 0, :reverse => false}
defaults = {:ordering => :<=>, :column => 0, :reverse => false}
opts = defaults.merge(opts)
opts = defaults.merge(opts)
Line 2,624: Line 2,624:
table.sort {|a, b| p.call(a[c], b[c])}
table.sort {|a, b| p.call(a[c], b[c])}
end
end
end</lang>
end</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
Line 2,632: Line 2,632:
Here we use Rust's "standard way" to have optional parameters, i.e. by using builders instead.
Here we use Rust's "standard way" to have optional parameters, i.e. by using builders instead.


<lang rust>use std::cmp::Ordering;
<syntaxhighlight lang="rust">use std::cmp::Ordering;


struct Table {
struct Table {
Line 2,771: Line 2,771:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Scala}}==
=={{header|Scala}}==
With Scala 2.8 optional and named parameters are build in.
With Scala 2.8 optional and named parameters are build in.
<lang scala> def sortTable(data: List[List[String]],
<syntaxhighlight lang="scala"> def sortTable(data: List[List[String]],
ordering: (String, String) => Boolean = (_ < _),
ordering: (String, String) => Boolean = (_ < _),
column: Int = 0,
column: Int = 0,
Line 2,781: Line 2,781:
val result = data.sortWith((a, b) => ordering(a(column), b(column)))
val result = data.sortWith((a, b) => ordering(a(column), b(column)))
if (reverse) result.reverse else result
if (reverse) result.reverse else result
}</lang>
}</syntaxhighlight>
<lang scala>val data=List(List("a","b","c"), List("","q","z"), List("zap","zip","Zot"))
<syntaxhighlight lang="scala">val data=List(List("a","b","c"), List("","q","z"), List("zap","zip","Zot"))
println(data)
println(data)
//-> List(List(a, b, c), List(, q, z), List(zap, zip, Zot))
//-> List(List(a, b, c), List(, q, z), List(zap, zip, Zot))
Line 2,792: Line 2,792:
//-> List(List(zap, zip, Zot), List(a, b, c), List(, q, z))
//-> List(List(zap, zip, Zot), List(a, b, c), List(, q, z))
println(sortTable(data, ((a, b)=> b.size<a.size)))
println(sortTable(data, ((a, b)=> b.size<a.size)))
//-> List(List(zap, zip, Zot), List(a, b, c), List(, q, z))</lang>
//-> List(List(zap, zip, Zot), List(a, b, c), List(, q, z))</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func table_sort(table, ordering: '<=>', column: 0, reverse: false) {
<syntaxhighlight lang="ruby">func table_sort(table, ordering: '<=>', column: 0, reverse: false) {
if (reverse) {
if (reverse) {
table.sort {|a,b| b[column].$ordering(a[column])}
table.sort {|a,b| b[column].$ordering(a[column])}
Line 2,810: Line 2,810:
];
];


say table_sort(table, column: 1);</lang>
say table_sort(table, column: 1);</syntaxhighlight>
{{out}}
{{out}}
<pre>[["Ottowa", "Canada"], ["Mexico City", "Mexico"], ["Washington", "USA"]]</pre>
<pre>[["Ottowa", "Canada"], ["Mexico City", "Mexico"], ["Washington", "USA"]]</pre>


Missing the point, we can also create and provide a custom method for sorting to ''ordering'':
Missing the point, we can also create and provide a custom method for sorting to ''ordering'':
<lang ruby>class String {
<syntaxhighlight lang="ruby">class String {
method my_sort(arg) {
method my_sort(arg) {
(self.len <=> arg.len) ->
(self.len <=> arg.len) ->
Line 2,823: Line 2,823:
}
}
say table_sort(table, column: 1, ordering: 'my_sort');</lang>
say table_sort(table, column: 1, ordering: 'my_sort');</syntaxhighlight>
{{out}}
{{out}}
<pre>[["Washington", "USA"], ["Ottowa", "Canada"], ["Mexico City", "Mexico"]]</pre>
<pre>[["Washington", "USA"], ["Ottowa", "Canada"], ["Mexico City", "Mexico"]]</pre>
Line 2,829: Line 2,829:
=={{header|Slate}}==
=={{header|Slate}}==
In Slate, named optional parameters may be specified in the method signature, but not defaults, so there is a macro <tt>defaultsTo:</tt> for specifying that within the method body at run-time.
In Slate, named optional parameters may be specified in the method signature, but not defaults, so there is a macro <tt>defaultsTo:</tt> for specifying that within the method body at run-time.
<lang slate>s@(Sequence traits) tableSort &column: column &sortBy: sortBlock &reverse: reverse
<syntaxhighlight lang="slate">s@(Sequence traits) tableSort &column: column &sortBy: sortBlock &reverse: reverse
[
[
column `defaultsTo: 0.
column `defaultsTo: 0.
Line 2,836: Line 2,836:
ifTrue: [sortBlock := [| :a :b | (sortBlock applyTo: {a. b}) not]].
ifTrue: [sortBlock := [| :a :b | (sortBlock applyTo: {a. b}) not]].
s sortBy: [| :a :b | sortBlock applyTo: {a at: column. b at: column}]
s sortBy: [| :a :b | sortBlock applyTo: {a at: column. b at: column}]
].</lang>
].</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>enum SortOrder { case kOrdNone, kOrdLex, kOrdByAddress, kOrdNumeric }
<syntaxhighlight lang="swift">enum SortOrder { case kOrdNone, kOrdLex, kOrdByAddress, kOrdNumeric }


func sortTable(table: [[String]], less: (String,String)->Bool = (<), column: Int = 0, reversed: Bool = false) {
func sortTable(table: [[String]], less: (String,String)->Bool = (<), column: Int = 0, reversed: Bool = false) {
// . . . Actual sort goes here . . .
// . . . Actual sort goes here . . .
}</lang>
}</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
Line 2,851: Line 2,851:
The optional positional parameter style works like this:<br>
The optional positional parameter style works like this:<br>
{{works with|Tcl|8.4}}
{{works with|Tcl|8.4}}
<lang tcl>proc tablesort {table {ordering ""} {column 0} {reverse 0}} {
<syntaxhighlight lang="tcl">proc tablesort {table {ordering ""} {column 0} {reverse 0}} {
set direction [expr {$reverse ? "-decreasing" : "-increasing"}]
set direction [expr {$reverse ? "-decreasing" : "-increasing"}]
if {$ordering ne ""} {
if {$ordering ne ""} {
Line 2,865: Line 2,865:
puts [tablesort $data {
puts [tablesort $data {
apply {{a b} {expr {[string length $a]-[string length $b]}}}
apply {{a b} {expr {[string length $a]-[string length $b]}}}
}]</lang>
}]</syntaxhighlight>


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.
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>
<br>
{{works with|Tcl|8.5}}
{{works with|Tcl|8.5}}
<lang Tcl>package require Tcl 8.5; # Only for the list expansion syntax
<syntaxhighlight lang="tcl">package require Tcl 8.5; # Only for the list expansion syntax


proc tablesort {table args} {
proc tablesort {table args} {
Line 2,887: Line 2,887:
puts [tablesort $data ordering {
puts [tablesort $data ordering {
apply {{a b} {expr {[string length $b]-[string length $a]}}}
apply {{a b} {expr {[string length $b]-[string length $a]}}}
}]</lang>
}]</syntaxhighlight>


=={{header|TIScript}}==
=={{header|TIScript}}==
Line 2,893: Line 2,893:
TIScript allows to define optional parameters with default values:
TIScript allows to define optional parameters with default values:


<lang javascript>function sorter(table, ordering = "lexicographic", column = 0, reverse = false) {
<syntaxhighlight lang="javascript">function sorter(table, ordering = "lexicographic", column = 0, reverse = false) {
// ...
// ...
}
}


sorter(the_data,"numeric");</lang>
sorter(the_data,"numeric");</syntaxhighlight>


=={{header|Unix Shell}}==
=={{header|Unix Shell}}==
{{works with|bash|4.2}}
{{works with|bash|4.2}}
<lang bash>#!/usr/bin/env bash
<syntaxhighlight lang="bash">#!/usr/bin/env bash
# sort-args.sh
# sort-args.sh


Line 2,937: Line 2,937:
echo sort numeric ; data | sort_table numeric
echo sort numeric ; data | sort_table numeric
echo sort numeric reverse ; data | sort_table numeric reverse
echo sort numeric reverse ; data | sort_table numeric reverse
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,986: Line 2,986:
that is applicable to a list of data to be sorted.
that is applicable to a list of data to be sorted.


<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import nat
#import nat


Line 2,995: Line 2,995:
reversed %b
reversed %b


sorter = +^(~reversed?/~&x! ~&!,-<+ +^/~ordering ~~+ ~&h++ //skip+ predecessor+ ~column)</lang>
sorter = +^(~reversed?/~&x! ~&!,-<+ +^/~ordering ~~+ ~&h++ //skip+ predecessor+ ~column)</syntaxhighlight>
Here is a test program using the function above to sort a table
Here is a test program using the function above to sort a table
five different ways, mentioning only the information that differs from the
five different ways, mentioning only the information that differs from the
defaults. The table is stored as a list of lists, with one list for each
defaults. The table is stored as a list of lists, with one list for each
row, hence three rows and two columns.
row, hence three rows and two columns.
<lang Ursala>example_table =
<syntaxhighlight lang="ursala">example_table =


<
<
Line 3,016: Line 3,016:
(sorter ss[column: 2]) example_table, # etc.
(sorter ss[column: 2]) example_table, # etc.
(sorter ss[reversed: true]) example_table,
(sorter ss[reversed: true]) example_table,
(sorter ss[reversed: true,column: 2]) example_table></lang>
(sorter ss[reversed: true,column: 2]) example_table></syntaxhighlight>
In practice, these five functions would have been more conveniently expressed using the
In practice, these five functions would have been more conveniently expressed using the
built in sort operator as <code>-<&h</code>, <code>leql-<&h</code>, <code>-<&th</code>, <code>-<x&h</code>, and <code>-<x&th</code>
built in sort operator as <code>-<&h</code>, <code>leql-<&h</code>, <code>-<&th</code>, <code>-<x&h</code>, and <code>-<x&th</code>
Line 3,029: Line 3,029:


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Private Sub optional_parameters(theRange As String, _
<syntaxhighlight lang="vb">Private Sub optional_parameters(theRange As String, _
Optional ordering As Integer = 0, _
Optional ordering As Integer = 0, _
Optional column As Integer = 1, _
Optional column As Integer = 1, _
Line 3,059: Line 3,059:
'Specifying reverse:=2 will sort in descending order.
'Specifying reverse:=2 will sort in descending order.
optional_parameters theRange:="A1:C4", ordering:=1, column:=2, reverse:=1
optional_parameters theRange:="A1:C4", ordering:=1, column:=2, reverse:=1
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
Line 3,065: Line 3,065:
{{libheader|Wren-seq}}
{{libheader|Wren-seq}}
Wren doesn't support optional parameters as such but does support method overloading by ''arity'' (i.e. number of parameters) which makes it easy to simulate them.
Wren doesn't support optional parameters as such but does support method overloading by ''arity'' (i.e. number of parameters) which makes it easy to simulate them.
<lang ecmascript>import "./sort" for Cmp, Sort
<syntaxhighlight lang="ecmascript">import "./sort" for Cmp, Sort
import "./seq" for Lst
import "./seq" for Lst


Line 3,110: Line 3,110:
System.print("\nAfter reverse lexicographic sort by second column:")
System.print("\nAfter reverse lexicographic sort by second column:")
table2 = TableSorter.sort(table, null, 1, true)
table2 = TableSorter.sort(table, null, 1, true)
System.print(table2.join("\n"))</lang>
System.print(table2.join("\n"))</syntaxhighlight>


{{out}}
{{out}}
Line 3,152: Line 3,152:
=={{header|XSLT}}==
=={{header|XSLT}}==
You can give any template parameter a default value using the optional "select" attribute.
You can give any template parameter a default value using the optional "select" attribute.
<lang xml><xsl:template name="sort">
<syntaxhighlight lang="xml"><xsl:template name="sort">
<xsl:param name="table" />
<xsl:param name="table" />
<xsl:param name="ordering" select="'lexicographic'" />
<xsl:param name="ordering" select="'lexicographic'" />
Line 3,158: Line 3,158:
<xsl:param name="reversed" select="false()" />
<xsl:param name="reversed" select="false()" />
...
...
</xsl:template></lang>
</xsl:template></syntaxhighlight>


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>sub power(n, p)
<syntaxhighlight lang="yabasic">sub power(n, p)
if numparams = 1 p = 2
if numparams = 1 p = 2
return n^p
return n^p
Line 3,167: Line 3,167:


print power(2)
print power(2)
print power(2, 3)</lang>
print power(2, 3)</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
zkl does left to right parameters, each with an optional default. No named parameters (ala Smalltalk). There isn't type enforcement either, a parameter can be anything (although you can set a hint to tell the compiler what you think it will be). If you do want to play named parameters, you can pass in a dictionary (ala Python). The parameters are basically a [varargs] list that you can access in traditional ways.
zkl does left to right parameters, each with an optional default. No named parameters (ala Smalltalk). There isn't type enforcement either, a parameter can be anything (although you can set a hint to tell the compiler what you think it will be). If you do want to play named parameters, you can pass in a dictionary (ala Python). The parameters are basically a [varargs] list that you can access in traditional ways.
<lang zkl>const lex="L";
<syntaxhighlight lang="zkl">const lex="L";
fcn mystrySort(table,ordering=lex,column=0,reverse=False,other){
fcn mystrySort(table,ordering=lex,column=0,reverse=False,other){
vm.arglist.println();
vm.arglist.println();
Line 3,180: Line 3,180:
mystrySort("table",lex,1,True,D("row",35,"type","foobar"));
mystrySort("table",lex,1,True,D("row",35,"type","foobar"));


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>