Jump to content

Rank (computer programming)

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by 2601:18f:600:e20:ccaa:ee1c:51aa:2ba9 (talk) at 20:27, 25 September 2016. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In computer programming, rank with no further specifications is usually a synonym for (or refers to) "number of dimensions"; thus, a two-dimensional array has rank two, a three-dimensional array has rank three and so on. Strictly, no formal definition can be provided which applies to every programming language, since each of them has its own concepts, semantics and terminology; the term may not even be applicable or, to the contrary, applied with a very specific meaning in the context of a given language.

In the case of APL the notion applies to every operand; and dyads ("binary functions") have a left rank and a right rank.

The box below instead shows how rank of a type and rank of an array expression could be defined (in a semi-formal style) for C++ and illustrates a simple way to calculate them at compile time.

#include <cstddef>
 
/* Rank of a type
 * -------------
 *
 * Let the rank of a type T be the number of its dimensions if
 * it is an array; zero otherwise (which is the usual convention)
 */
template <typename t> struct rank
{ static const std::size_t value = 0; };

template<typename t, std::size_t n>
struct rank<t[n]>
{ static const std::size_t value = 1 + rank<t>::value; };

/* Rank of an expression
 *
 * Let the rank of an expression be the rank of its type
 */
template <typename t, std::size_t n>
char(&rankof(t(&)[n]))[n];

Given the code above the rank of a type T can be calculated at compile time by

rank<T>::value

and the rank of an array-expression expr by

sizeof(rankof(expr))

See also