Optional parameters: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Phix}}: added syntax colouring the hard way, phix/basics)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(14 intermediate revisions by 9 users not shown)
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.
 
<langsyntaxhighlight Adalang="ada">package Tables is
 
type Table is private;
Line 41:
private
... -- implementation specific
end Tables;</langsyntaxhighlight>
 
example of use:
<langsyntaxhighlight Adalang="ada">with Tables;
procedure Table_Test is
My_Table : Tables.Table;
Line 53:
Sort (It => My_Table, Reverse_Ordering => True); -- use default sorting in reverse order
... -- other stuff
end Table_Test;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight 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 #
# with elements of these types #
Line 90:
configurable sort( data, ( 2, ( STRING a, STRING b )INT: default compare( a[ LWB a + 1 : ], b[ LWB b + 1 : ] ) ) );
# default sort #
configurable sort( data, () )</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight AppleScriptlang="applescript">on sortTable(x)
set {sortOrdering, sortColumn, sortReverse} to {sort_lexicographic, 1, false}
try
Line 113:
return table
end sort
end script</langsyntaxhighlight>
Examples of use:
<langsyntaxhighlight AppleScriptlang="applescript">-- Another sort function.
script sort_colex
on sort(table, column, reverse)
Line 129:
sortTable({sequence:table, ordering:sort_colex, column:2, reverse:true})
sortTable({sequence:table, reverse:true})
sortTable({sequence:table})</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">sortTable: function [tbl][
column: "0"
reversed?: false
unless null? c: <= attr 'column -> column: to :string c
unless null? attr 'reverse -> reversed?: true
 
result: new sort.by: column map tbl 'r [
to :dictionary flatten couple 0..dec size r r
]
 
if reversed? -> reverse 'result
 
return map result 'r -> values r
]
 
printTable: function [tbl, title][
print ["==" title]
loop tbl 'row [
print row
]
print ""
]
 
lst: [
["a", "b", "c"]
["", "q", "z"]
["zap", "zip", "Zot"]
]
 
printTable sortTable lst "Default sort"
printTable sortTable.column:1 lst "Sorting by column=1"
printTable sortTable.reverse lst "Sorting, reversed"
printTable sortTable.reverse.column:1 lst "Sorting by column=1, reversed"</syntaxhighlight>
 
{{out}}
 
<pre>== Default sort
q z
a b c
zap zip Zot
 
== Sorting by column=1
a b c
q z
zap zip Zot
 
== Sorting, reversed
zap zip Zot
a b c
q z
 
== Sorting by column=1, reversed
zap zip Zot
q z
a b c</pre>
 
=={{header|AutoHotkey}}==
built in support for table sorting is available through the standard Win32 listview.
<langsyntaxhighlight AutoHotkeylang="autohotkey">Gosub start ; create and show the gui
sort_table("Text", column := 2, reverse := 1) ; lexicographic sort
Sleep, 2000
Line 165 ⟶ 223:
 
GuiClose:
ExitApp</langsyntaxhighlight>
 
=={{header|BASIC}}==
Line 189 ⟶ 247:
=={{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.
<langsyntaxhighlight lang="bbcbasic"> DIM table$(100,100)
PROCsort_default(table$())
PROCsort_options(table$(), TRUE, 1, FALSE)
Line 198 ⟶ 256:
REM The sort goes here, controlled by the options
REM Zero/FALSE values for the options shall select the defaults
ENDPROC</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="bracmat">( ( sortTable
= table ordering column reverse
. !arg
Line 223 ⟶ 281:
: ?table
& sortTable$(!table.(column.2) (reverse.yes))
);</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
Line 392 ⟶ 450:
printTable(&table, stdout, colFmts);
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
This implementation only accepts function pointers for the comparators, and does not accept function objects, for simplicity.
<langsyntaxhighlight lang="cpp">#include <vector>
#include <algorithm>
#include <string>
Line 486 ⟶ 544:
 
return 0;
}</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight Clojurelang="clojure">(defn sort [table & {:keys [ordering column reverse?]
:or {ordering :lex, column 1}}]
(println table ordering column reverse?))
 
(sort [1 8 3] :reverse? true)
[1 8 3] :lex 1 true</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Line 502 ⟶ 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.
 
<langsyntaxhighlight lang="lisp">(defun sort-table (table &key (ordering #'string<)
(column 0)
reverse)
Line 508 ⟶ 566:
(complement ordering)
ordering)
:key (lambda (row) (elt row column))))</langsyntaxhighlight>
 
(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:
<langsyntaxhighlight lang="lisp">CL-USER> (defparameter *data* '(("a" "b" "c") ("" "q" "z") ("zap" "zip" "Zot")))
*DATA*
 
Line 529 ⟶ 587:
 
CL-USER> (sort-table *data* :ordering (lambda (a b) (> (length a) (length b))))
(("zap" "zip" "Zot") ("a" "b" "c") ("" "q" "z"))</langsyntaxhighlight>
 
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.functional;
 
string[][] sortTable(string[][] table,
Line 560 ⟶ 618:
show(sortTable(data, null, 1, true));
show(sortTable(data, (a,b) => b.length > a.length));
}</langsyntaxhighlight>
{{out}}
<pre>["a", "b", "c"]
Line 590 ⟶ 648:
{{libheader| System.SysUtils}}
{{Trans|D}}
<langsyntaxhighlight Delphilang="delphi">program Optional_parameters;
 
{$APPTYPE CONSOLE}
Line 755 ⟶ 813:
end).ToString, #10);
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 790 ⟶ 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'').
 
<langsyntaxhighlight lang="e">def defaultOrdering(a, b) { return a.op__cmp(b) }
 
def sort {
Line 811 ⟶ 869:
}
 
}</langsyntaxhighlight>
 
Named parameters are not builtin, but map-patterns may be used as a substitute. (TODO: Example of this) [[Category:E examples needing attention]]
 
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module OptionalParameters {
typedef Type<String >.Orderer as ColumnOrderer;
typedef Type<String[]>.Orderer as RowOrderer;
 
static String[][] sort(String[][] table,
ColumnOrderer? orderer = Null,
Int column = 0,
Boolean reverse = False,
) {
// provide a default orderer
orderer ?:= (s1, s2) -> s1 <=> s2;
 
// optionally reverse the order
ColumnOrderer byString = reverse
? ((s1, s2) -> orderer(s1, s2).reversed)
: orderer;
 
// sort the indicated column
RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]);
 
return table.sorted(byColumn);
}
 
void run() {
String[][] table =
[
["c", "x", "i"],
["a", "y", "p"],
["b", "z", "a"],
];
 
show("original input", table);
show("by default sort on column 0", sort(table));
show("by column 2", sort(table, column=2));
show("by column 2 reversed", sort(table, column=2, reverse=True));
}
 
void show(String title, String[][] table) {
@Inject Console console;
console.print($"{title}:");
for (val row : table) {
console.print($" {row}");
}
console.print();
}
}
</syntaxhighlight>
 
{{out}}
<pre>
original input:
[c, x, i]
[a, y, p]
[b, z, a]
 
by default sort on column 0:
[a, y, p]
[b, z, a]
[c, x, i]
 
by column 2:
[b, z, a]
[c, x, i]
[a, y, p]
 
by column 2 reversed:
[a, y, p]
[c, x, i]
[b, z, a]
</pre>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Optional_parameters do
def sort( table, options\\[] ) do
options = options ++ [ ordering: :lexicographic, column: 0, reverse: false ]
Line 847 ⟶ 978:
end
 
Optional_parameters.task</langsyntaxhighlight>
 
{{out}}
Line 860 ⟶ 991:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( optional_parameters ).
 
Line 900 ⟶ 1,031:
table_row2() -> {"456", "0789", "123"}.
table_row3() -> {"0789", "123", "456"}.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 921 ⟶ 1,052:
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.
 
<langsyntaxhighlight lang="fsharp">type Table(rows:string[][]) =
// in-place sorting of rows
member x.Sort(?ordering, ?column, ?reverse) =
Line 957 ⟶ 1,088:
 
t.Sort(ordering=fun s1 s2 -> compare s2.Length s1.Length)
printfn "Sorted by decreasing length"; t.Print()</langsyntaxhighlight>
 
Output:
Line 987 ⟶ 1,118:
=={{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.
<langsyntaxhighlight lang="factor">USING: accessors combinators io kernel math.order prettyprint
sequences sorting ;
 
Line 1,044 ⟶ 1,175:
t >>reversed?
[ length ] >>ordering
sort-table simple-table.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,078 ⟶ 1,209:
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).
 
<langsyntaxhighlight lang="fortran">module ExampleOptionalParameter
! use any module needed for the sort function(s)
! and all the interfaces needed to make the code work
Line 1,146 ⟶ 1,277:
end subroutine sort_table
 
end module ExampleOptionalParameter</langsyntaxhighlight>
 
<langsyntaxhighlight lang="fortran">program UsingTest
use ExampleOptionalParameter
implicit none
Line 1,183 ⟶ 1,314:
call sort_table(table, column=2)
 
end program UsingTest</langsyntaxhighlight>
 
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">Function power(n As Integer, p As Integer = 2) As Double
Return n ^ p
End Function
 
Print power(2) ' muestra 4
Print power(2, 3) ' muestra 8
Sleep</syntaxhighlight>
 
 
=={{header|Go}}==
Line 1,200 ⟶ 1,342:
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.
 
<langsyntaxhighlight lang="go">type cell string
 
type spec struct {
Line 1,219 ⟶ 1,361:
s := newSpec
s.reverse = true
t.sort(s)</langsyntaxhighlight>
 
===Struct literal with keyed elements===
Line 1,225 ⟶ 1,367:
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,
<langsyntaxhighlight lang="go">type spec struct {
ordering func(cell, cell) bool
column int
reverse bool
}</langsyntaxhighlight>
the following struct literal fills in zero values for ordering and column and assigns true to the field reverse.
<syntaxhighlight lang ="go">spec{reverse: true}</langsyntaxhighlight>
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,237 ⟶ 1,379:
 
Nevertheless, a complete program to demonstrate:
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,329 ⟶ 1,471:
})
t.printRows("sorted by descending string length on second column")
}</langsyntaxhighlight>
Output:
<pre>
Line 1,364 ⟶ 1,506:
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:
 
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,475 ⟶ 1,617:
t.sort(column(1), ordering(byLen))
t.printRows("sorted by descending string length on second column")
}</langsyntaxhighlight>
Output same as previous solution.
 
=={{header|Groovy}}==
Optional Parameters:
<langsyntaxhighlight 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])}
}</langsyntaxhighlight>
 
Test code:
<langsyntaxhighlight lang="groovy">def table = [['a', 'b', 'c'], ['', 'q', 'z'], ['zap', 'zip', 'Zot']]
 
assert orderedSort(table) == [['', 'q', 'z'], ['a', 'b', 'c'], ['zap', 'zip', 'Zot']]
Line 1,491 ⟶ 1,633:
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, 0, false, {x, y -> y?.size() <=> x?.size()} as Comparator) == [['zap', 'zip', 'Zot'],['a', 'b', 'c'],['', 'q', 'z']]</langsyntaxhighlight>
 
Named Parameters:
<langsyntaxhighlight lang="groovy">Collection.metaClass.orderedSort = { params ->
def column = params?.column ?: 0
def reverse = params?.reverse ?: false
Line 1,500 ⟶ 1,642:
 
table.sort(false) { x, y -> (reverse ? -1 : 1) * ordering.compare(x[column], y[column])}
}</langsyntaxhighlight>
 
Test Code:
 
<langsyntaxhighlight lang="groovy">def table = [['a', 'b', 'c'], ['', 'q', 'z'], ['zap', 'zip', 'Zot']]
 
assert table.orderedSort() == [['', 'q', 'z'], ['a', 'b', 'c'], ['zap', 'zip', 'Zot']]
Line 1,510 ⟶ 1,652:
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(ordering: {x, y -> y?.size() <=> x?.size()} as Comparator) == [['zap', 'zip', 'Zot'],['a', 'b', 'c'],['', 'q', 'z']]</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="haskell">
{-# LANGUAGE RecordWildCards #-}
 
Line 1,530 ⟶ 1,672:
sorter defSortArgs [[]]
return ()
</syntaxhighlight>
</lang>
 
Option 2: This method has the drawback of being a bit verbose and requiring you to supply "Maybe a" arguments.
<langsyntaxhighlight lang="haskell">
import Data.Maybe (fromMaybe)
-- Use fromMaybe as an operator because its prettier
Line 1,546 ⟶ 1,688:
sorter (Just "foo") (Just 1) (Just True)
sorter Nothing Nothing Nothing
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight Iconlang="icon">
procedure main()
X := [ [1,2,3], [2,3,1], [3,1,2]) # A list of lists
Line 1,570 ⟶ 1,712:
}
return (\reverseorder|1)(bubblesortf(X,\c|1,\op|"<<")) # reverse or return the sorted list
end</langsyntaxhighlight>
 
=={{header|J}}==
 
<langsyntaxhighlight lang="j">srtbl=: verb define
'' srtbl y
:
'`ordering column reverse'=. x , (#x)}. ]`0:`0:
|.^:reverse y /: ordering (column {"1 ])y
)</langsyntaxhighlight>
 
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'''
<langsyntaxhighlight lang="j"> ]Table=: ('a';'b';'c'),('';'q';'z'),:'zip';'zap';'Zot'
┌───┬───┬───┐
│a │b │c │
Line 1,623 ⟶ 1,765:
├───┼───┼───┤
│zip│zap│Zot│
└───┴───┴───┘</langsyntaxhighlight>
 
=={{header|Java}}==
Line 1,629 ⟶ 1,771:
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.
 
<langsyntaxhighlight lang="java">import java.util.*;
 
public class OptionalParams {
Line 1,701 ⟶ 1,843:
// prints: [[zap, zip, Zot], [a, b, c], [, q, z]]
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
See [[Named parameters#JavaScript]], to pass named parameters one uses an object with properties set:
<langsyntaxhighlight lang="javascript">function sorter(table, options) {
opts = {}
opts.ordering = options.ordering || 'lexicographic';
Line 1,714 ⟶ 1,856:
}
 
sorter(the_data, {reverse: true, ordering: 'numeric'});</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,744 ⟶ 1,886:
interpreted by jq. The key to understanding this is that jq functions
are compiled into closures. Here is an example:
<langsyntaxhighlight lang="jq">def bar: 2 *.;
 
def foo: {"a": bar};</langsyntaxhighlight>
The expression <tt>3 | foo.a</tt> evaluates to 6.
 
Line 1,753 ⟶ 1,895:
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:
<langsyntaxhighlight lang="jq">def less_than_or_equal: .[0] <= .[1];</langsyntaxhighlight>
 
'''The Task''':
<langsyntaxhighlight lang="jq">def sorter(options):
sort_table( if (options|has("ordering")) then options.ordering
else less_than_or_equal
Line 1,764 ⟶ 1,906:
 
# If jq > 1.4 is being used, we may also define:
def sorter: sorter({});</langsyntaxhighlight>
'''Examples''':
<langsyntaxhighlight lang="jq">[1,2] | sorter({ "reverse": true, "ordering": less_than_or_equal } )
 
[1,2] | sorter({ "reverse": true })
 
# If sorter/0 has also been defined:
[1,2] | sorter</langsyntaxhighlight>
 
=={{header|Julia}}==
Julia supports both named and positional optional parameters. We can define both versions at the same time if we want:
<langsyntaxhighlight lang="julia">sorttable(T; ordering=<, column=1, reverse=false) =
sort(T, by = t -> t[column], lt = reverse ? (a,b) -> ordering(b,a) : ordering)
sorttable(T, ordering=<, column=1, reverse=false) =
sorttable(T, ordering=ordering, column=column, reverse=reverse)</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="julia">julia> data = {["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]}
3-element Array{Any,1}:
["a","b","c"]
Line 1,798 ⟶ 1,940:
["zap","zip","Zot"]
["","q","z"]
["a","b","c"] </langsyntaxhighlight>
 
=={{header|Klingphix}}==
<langsyntaxhighlight Klingphixlang="klingphix">include ..\Utilitys.tlhy
 
:mypower
Line 1,815 ⟶ 1,957:
"2 ^3 = " print ( 2 3 ) mypower ?
 
"End " input</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.51
 
typealias Table = List<List<String>>
Line 1,863 ⟶ 2,005:
val table3 = table.sort(ordering = comp)
table3.print("Reverse case insensitive sort by col 2:")
}</langsyntaxhighlight>
 
{{out}}
Line 1,910 ⟶ 2,052:
=={{header|Lasso}}==
Lasso can handle both positional and named params. Methods support multiple dispatch where each dispatch defines it's own set of parameters.
<langsyntaxhighlight Lassolang="lasso">define sortarray( // params are set by position
items::array, // required param
ordering::string = 'lexicographic', // optional param
Line 1,942 ⟶ 2,084:
sortarray(-items = #items, -reverse)
 
sortarray(#items)</langsyntaxhighlight>
 
=={{header|Logo}}==
{{works with|UCB Logo}}
<langsyntaxhighlight lang="logo">to sort :table [:column 1] [:ordering "before?] [:reverse "false]
; ...
end</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="logo">sort :table
(sort :table 2)
(sort :table 3 "less? "true)</langsyntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">
<lang Lua>
function showTable(tbl)
if type(tbl)=='table' then
Line 1,999 ⟶ 2,141:
sortTable{table=A, cmp=(function (a, b) return #a < #b end)}
print('by length', showTable(A))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,011 ⟶ 2,153:
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
OptionalSort := proc(input, {
ordering :: Or(procedures,identical("lexicographic")) := "lexicographic",
Line 2,024 ⟶ 2,166:
end if;
sort( input, compare );
end proc:</langsyntaxhighlight>
 
Some examples of this procedure in action:
<syntaxhighlight lang="maple">
<lang Maple>
> L := [[1, 2], [3, 4], [-5, 7]]:
> OptionalSort(L);
Line 2,035 ⟶ 2,177:
> OptionalSort(L, reverse, column = 2);
[[-5, 7], [3, 4], [1, 2]]
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Options[OptionalSort]={ordering->lexicographic,column->1,reverse-> False};
OptionalSort[x_List,OptionsPattern[]]:=If[OptionValue[reverse]==True,
SortBy[x ,#[[OptionValue[column]]]&]//Reverse,
Line 2,047 ⟶ 2,189:
 
OptionalSort[{{"a" ,"b", "c"}, {"", "q", "z"},{"zap" ,"zip", "Zot"}},{ordering->lexicographic,column->2,reverse-> True} ]
->{{zap,zip,Zot},{,q,z},{a,b,c}}</langsyntaxhighlight>
 
=={{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).
<langsyntaxhighlight Nemerlelang="nemerle">Sorter (table : list[list[string]], ordering = "lexicographic", column = 0, reverse = false) : list[list[string]]
{
// implementation goes here
}</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import algorithm, strutils, sugar
 
proc printTable(a: seq[seq[string]]) =
Line 2,078 ⟶ 2,220:
printTable sortTable(data, column = 1)
printTable sortTable(data, column = 1, reverse = true)
printTable sortTable(data, ordering = (a,b) => cmp[int](b.len,a.len))</langsyntaxhighlight>
Output:
<pre>a b c
Line 2,106 ⟶ 2,248:
=={{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.)
<langsyntaxhighlight lang="objc">typedef enum { kOrdNone, kOrdLex, kOrdByAddress, kOrdNumeric } SortOrder;
 
@interface MyArray : NSObject {}
Line 2,130 ⟶ 2,272:
}
 
@end</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 2,136 ⟶ 2,278:
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.
 
<langsyntaxhighlight 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
List.sort cmp table</langsyntaxhighlight>
 
Example uses:
<langsyntaxhighlight lang="ocaml"># let data = [["a"; "b"; "c"]; [""; "q"; "z"]; ["zap"; "zip"; "Zot"]];;
val data : string list list =
[["a"; "b"; "c"]; [""; "q"; "z"]; ["zap"; "zip"; "Zot"]]
Line 2,158 ⟶ 2,300:
# sort_table ~ordering:(fun a b -> compare (String.length b) (String.length a)) data;;
- : string list list =
[["zap"; "zip"; "Zot"]; ["a"; "b"; "c"]; [""; "q"; "z"]]</langsyntaxhighlight>
 
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,164 ⟶ 2,306:
=={{header|Oz}}==
Oz supports optional parameters only for methods, not for functions.
<langsyntaxhighlight lang="oz">declare
class Table
attr
Line 2,193 ⟶ 2,335:
{T sort(column:2)}
{T sort(column:2 reverse:true)}
{T sort(ordering:fun {$ A B} {Length B} < {Length A} end)}</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight lang="parigp">sort(v, ordering=0, column=0, reverse=0)</langsyntaxhighlight>
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");
*/
Line 2,208 ⟶ 2,350:
else
pari_printf("Argument was: %Ps\n", x);
}</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 2,215 ⟶ 2,357:
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.
 
<langsyntaxhighlight lang="perl">sub sorttable
{my @table = @{shift()};
my %opt =
Line 2,224 ⟶ 2,366:
{$func->($a->[$col], $b->[$col])}
@table;
return ($opt{reverse} ? [reverse @result] : \@result);}</langsyntaxhighlight>
 
An example of use:
 
<langsyntaxhighlight lang="perl">my $a = [["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]];
foreach (@{sorttable $a, column => 1, reverse => 1})
{foreach (@$_)
{printf "%-5s", $_;}
print "\n";}</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 2,238 ⟶ 2,380:
Optional parameters are specified simply by declaring a default value. They must however be grouped on the right.
 
<!--<langsyntaxhighlight Phixlang="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;">return</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">inc</span>
Line 2,245 ⟶ 2,387:
<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>
<!--</langsyntaxhighlight>-->
 
You can also use a variable length sequence to emulate optional parameters.
 
<!--<langsyntaxhighlight Phixlang="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>
<!--</langsyntaxhighlight>-->
 
In other words printf always accepts exactly three arguments, but the third should contain the correct number of
Line 2,258 ⟶ 2,400:
The following incomplete snippet from demo\pGUI\listview.exw shows the basic idea for sorting a table by any column, up or down:
 
<!--<langsyntaxhighlight Phixlang="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: #000000;">sortdir</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
Line 2,280 ⟶ 2,422:
<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>
<!--</langsyntaxhighlight>-->
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def mypower
1 tolist flatten len
1 == if
Line 2,295 ⟶ 2,437:
 
"2 ^2 = " print 2 mypower print nl
"2 ^3 = " print 2 3 2 tolist mypower print</langsyntaxhighlight>
More elegant.
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
def mypower
Line 2,310 ⟶ 2,452:
 
"2 ^2: " print 2 mypower ?
"2 ^3: " print ( 2 3 ) mypower ?</langsyntaxhighlight>
More in line with the task description
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
( ( "a" "b" "c" )
Line 2,344 ⟶ 2,486:
( 2 ) mysort pstack
( 2 true ) mysort pstack
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,360 ⟶ 2,502:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de sortTable (Tbl . @)
(let (Ordering prog Column 1 Reverse NIL) # Set defaults
(bind (rest) # Bind optional params
Line 2,367 ⟶ 2,509:
sort
Tbl ) )
(if Reverse (flip Tbl) Tbl) ) ) )</langsyntaxhighlight>
Output:
<pre>(de *Data ("a" "bcdef" "X") (" " "qrst" "z") ("zap" "zip" "Zot"))
Line 2,387 ⟶ 2,529:
 
Using a pretty-printer for the table
<langsyntaxhighlight lang="python">>>> def printtable(data):
for row in data:
print ' '.join('%-5s' % ('"%s"' % cell) for cell in row)
Line 2,421 ⟶ 2,563:
"a" "b" "c"
"" "q" "z"
>>></langsyntaxhighlight>
 
See the Python entry in [[Named_Arguments#Python|Named Arguments]] for a more comprehensive description of Python function parameters and call arguments.
Line 2,441 ⟶ 2,583:
=={{header|R}}==
Optional parameters are given using a name=value syntax within the function header.
<langsyntaxhighlight Rlang="r">tablesort <- function(x, ordering="lexicographic", column=1, reverse=false)
{
# Implementation
Line 2,447 ⟶ 2,589:
 
# Usage is e.g.
tablesort(mytable, column=3)</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 2,462 ⟶ 2,604:
ordering)
#:key (λ (row) (list-ref row column))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
Using named parameters:
<syntaxhighlight lang="raku" perl6line>method sorttable(:$column = 0, :$reverse, :&ordering = &infix:<cmp>) {
my @result = self»[$column].sort: &ordering;
return $reverse ?? @result.reverse !! @result;
}</langsyntaxhighlight>
 
Using optional positional parameters:
<syntaxhighlight lang="raku" perl6line>method sorttable-pos($column = 0, $reverse?, &ordering = &infix:<cmp>) {
my @result = self»[$column].sort: &ordering;
return $reverse ?? @result.reverse !! @result;
}</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 2,482 ⟶ 2,624:
<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.
<langsyntaxhighlight lang="rexx">sortStrings: procedure expose @. /*the stemmed array is named: @. */
col= 1 /*set some defaults (here and below). */
reverse= 'NO'
Line 2,504 ⟶ 2,646:
... main body of string sort here ...
 
return /*stick a fork in it, we're all done. */</langsyntaxhighlight>
An example use is:
<langsyntaxhighlight lang="rexx">/*REXX example uses the SortStrings subroutine with some (passed) optional arguments. */
 
 
Line 2,513 ⟶ 2,655:
 
call sortStrings 'Reverse=no' 3
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
 
=={{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''.
 
<langsyntaxhighlight lang="ruby">def table_sort(table, ordering=:<=>, column=0, reverse=false)
# ...</langsyntaxhighlight>
 
Ruby 2.0 added keyword arguments to the language. These provide the most natural solution.
 
{{works with|Ruby|2.0}}
<langsyntaxhighlight lang="ruby">def table_sort(table, ordering: :<=>, column: 0, reverse: false)
p = ordering.to_proc
if reverse
Line 2,539 ⟶ 2,681:
["Mexico City", "Mexico"],
]
p table_sort(table, column: 1)</langsyntaxhighlight>
 
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}}
<langsyntaxhighlight lang="ruby">def table_sort(table, opts = {})
defaults = {:ordering => :<=>, :column => 0, :reverse => false}
opts = defaults.merge(opts)
Line 2,555 ⟶ 2,697:
table.sort {|a, b| p.call(a[c], b[c])}
end
end</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 2,563 ⟶ 2,705:
Here we use Rust's "standard way" to have optional parameters, i.e. by using builders instead.
 
<langsyntaxhighlight lang="rust">use std::cmp::Ordering;
 
struct Table {
Line 2,702 ⟶ 2,844:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
With Scala 2.8 optional and named parameters are build in.
<langsyntaxhighlight lang="scala"> def sortTable(data: List[List[String]],
ordering: (String, String) => Boolean = (_ < _),
column: Int = 0,
Line 2,712 ⟶ 2,854:
val result = data.sortWith((a, b) => ordering(a(column), b(column)))
if (reverse) result.reverse else result
}</langsyntaxhighlight>
<langsyntaxhighlight lang="scala">val data=List(List("a","b","c"), List("","q","z"), List("zap","zip","Zot"))
println(data)
//-> List(List(a, b, c), List(, q, z), List(zap, zip, Zot))
Line 2,723 ⟶ 2,865:
//-> List(List(zap, zip, Zot), List(a, b, c), List(, q, z))
println(sortTable(data, ((a, b)=> b.size<a.size)))
//-> List(List(zap, zip, Zot), List(a, b, c), List(, q, z))</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func table_sort(table, ordering: '<=>', column: 0, reverse: false) {
if (reverse) {
table.sort {|a,b| b[column].$ordering(a[column])}
Line 2,741 ⟶ 2,883:
];
 
say table_sort(table, column: 1);</langsyntaxhighlight>
{{out}}
<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'':
<langsyntaxhighlight lang="ruby">class String {
method my_sort(arg) {
(self.len <=> arg.len) ->
Line 2,754 ⟶ 2,896:
}
say table_sort(table, column: 1, ordering: 'my_sort');</langsyntaxhighlight>
{{out}}
<pre>[["Washington", "USA"], ["Ottowa", "Canada"], ["Mexico City", "Mexico"]]</pre>
Line 2,760 ⟶ 2,902:
=={{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.
<langsyntaxhighlight lang="slate">s@(Sequence traits) tableSort &column: column &sortBy: sortBlock &reverse: reverse
[
column `defaultsTo: 0.
Line 2,767 ⟶ 2,909:
ifTrue: [sortBlock := [| :a :b | (sortBlock applyTo: {a. b}) not]].
s sortBy: [| :a :b | sortBlock applyTo: {a at: column. b at: column}]
].</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">enum SortOrder { case kOrdNone, kOrdLex, kOrdByAddress, kOrdNumeric }
 
func sortTable(table: [[String]], less: (String,String)->Bool = (<), column: Int = 0, reversed: Bool = false) {
// . . . Actual sort goes here . . .
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
Line 2,782 ⟶ 2,924:
The optional positional parameter style works like this:<br>
{{works with|Tcl|8.4}}
<langsyntaxhighlight lang="tcl">proc tablesort {table {ordering ""} {column 0} {reverse 0}} {
set direction [expr {$reverse ? "-decreasing" : "-increasing"}]
if {$ordering ne ""} {
Line 2,796 ⟶ 2,938:
puts [tablesort $data {
apply {{a b} {expr {[string length $a]-[string length $b]}}}
}]</langsyntaxhighlight>
 
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}}
<langsyntaxhighlight Tcllang="tcl">package require Tcl 8.5; # Only for the list expansion syntax
 
proc tablesort {table args} {
Line 2,818 ⟶ 2,960:
puts [tablesort $data ordering {
apply {{a b} {expr {[string length $b]-[string length $a]}}}
}]</langsyntaxhighlight>
 
=={{header|TIScript}}==
Line 2,824 ⟶ 2,966:
TIScript allows to define optional parameters with default values:
 
<langsyntaxhighlight lang="javascript">function sorter(table, ordering = "lexicographic", column = 0, reverse = false) {
// ...
}
 
sorter(the_data,"numeric");</langsyntaxhighlight>
 
=={{header|UnixUNIX Shell}}==
{{works with|bash|4.2}}
<langsyntaxhighlight lang="bash">#!/usr/bin/env bash
# sort-args.sh
 
Line 2,868 ⟶ 3,010:
echo sort numeric ; data | sort_table numeric
echo sort numeric reverse ; data | sort_table numeric reverse
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,917 ⟶ 3,059:
that is applicable to a list of data to be sorted.
 
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 2,926 ⟶ 3,068:
reversed %b
 
sorter = +^(~reversed?/~&x! ~&!,-<+ +^/~ordering ~~+ ~&h++ //skip+ predecessor+ ~column)</langsyntaxhighlight>
Here is a test program using the function above to sort a table
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
row, hence three rows and two columns.
<langsyntaxhighlight Ursalalang="ursala">example_table =
 
<
Line 2,947 ⟶ 3,089:
(sorter ss[column: 2]) example_table, # etc.
(sorter ss[reversed: true]) example_table,
(sorter ss[reversed: true,column: 2]) example_table></langsyntaxhighlight>
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>
Line 2,960 ⟶ 3,102:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Private Sub optional_parameters(theRange As String, _
Optional ordering As Integer = 0, _
Optional column As Integer = 1, _
Line 2,990 ⟶ 3,132:
'Specifying reverse:=2 will sort in descending order.
optional_parameters theRange:="A1:C4", ordering:=1, column:=2, reverse:=1
End Sub</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-sort}}
{{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.
<langsyntaxhighlight ecmascriptlang="wren">import "./sort" for Cmp, Sort
import "./seq" for Lst
 
class TableSorter {
Line 3,003 ⟶ 3,147:
if (ordering == null) ordering = Fn.new { |r1, r2| Cmp.string.call(r1[column], r2[column]) }
var sorted = Sort.merge(table, ordering)
if (reverse) SortLst.reverse(sorted)
return sorted
}
Line 3,039 ⟶ 3,183:
System.print("\nAfter reverse lexicographic sort by second column:")
table2 = TableSorter.sort(table, null, 1, true)
System.print(table2.join("\n"))</langsyntaxhighlight>
 
{{out}}
Line 3,081 ⟶ 3,225:
=={{header|XSLT}}==
You can give any template parameter a default value using the optional "select" attribute.
<langsyntaxhighlight lang="xml"><xsl:template name="sort">
<xsl:param name="table" />
<xsl:param name="ordering" select="'lexicographic'" />
Line 3,087 ⟶ 3,231:
<xsl:param name="reversed" select="false()" />
...
</xsl:template></langsyntaxhighlight>
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">sub power(n, p)
if numparams = 1 p = 2
return n^p
Line 3,096 ⟶ 3,240:
 
print power(2)
print power(2, 3)</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="zkl">const lex="L";
fcn mystrySort(table,ordering=lex,column=0,reverse=False,other){
vm.arglist.println();
Line 3,109 ⟶ 3,253:
mystrySort("table",lex,1,True,D("row",35,"type","foobar"));
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,119 ⟶ 3,263:
 
 
{{omit from|Factor}}
{{omit from|GUISS}}
{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}}
9,476

edits