# rank

## rank() sort T.s : ‘s 🡒 T.rk : number, process

Returns the ranks, starting at 1, of the values, in decreasing order, with no tie. Tie-breaks are arbitrary.

Example:

table T = with
[| as N |]
[| 0 |]
[| 1 |]
[| 2 |]
[| 3 |]

T.rk = rank() sort T.N

show table "" a1b4 with
T.N
T.rk


## rank() by T.g : ‘g sort T.s : ‘s 🡒 T.rk : number, process

For every group identified by T.g, returns the ranks, starting at 1, of the values, in decreasing order, with no tie. Tie-breaks are arbitrary.

Example:

table T = with
[| as N, as G |]
[| 0, "a" |]
[| 1, "a" |]
[| 2, "b" |]
[| 3, "b" |]

T.rk = rank() by T.G sort T.N

show table "" a1c4 with
T.G
T.N
T.rk


## rank(T.n : ‘n, T.g : ‘g, T.s : ‘s) 🡒 T.rk : number, process

The purpose of this rank overload is to support the generation of a prioritized purchase list. In particular, this overload cannot be re-expressed as a simple expression of sorting and grouping. This is a two-stage imperative algorithm. In the first stage, values are grouped by T.g into stacks, with each stack ordered by ascending T.s. In the second stage, the algorithm selects the highest value of T.n among the top elements of all stacks, pops that element, assigns it a rank (starting at 1), and repeats until all stacks are empty.

Example:

table T = with
[| as N, as G, as S |]
[| 0, "a", 1 |]
[| 1, "a", 0 |]
[| 2, "b", 1 |]
[| 3, "b", 0 |]

T.rk = rank(T.N, T.G, T.S)

show table "" a1d4 with
T.G
T.N
T.S
T.rk