[ Term Manipulation | Reference Manual | Alphabetic Index ]

array_flat(+N, +Array, -Flat)

Flattens (reduces the number of dimensions) of a multi-dimensional array
N
Integer
Array
Array, i.e. structure with functor []/?
Flat
Variable or array

Description

Constructs an array Flat with the same elements, but N fewer dimensions than Array. The most common use is to create a flat, one-dimensional array from a multi-dimensional one. Note that multi-dimensional arrays are in fact nested one-dimensional arrays.

N specifies how many levels are flattened: a positive value N means that a M-dimensional array will be reduced to a (M-N)-dimensional one, e.g. a 2-D array gets reduced to a 1-D array. When N is given as -1, all array nesting is removed, and a 1-D array on the non-array elements is produced. In practice, it is however recommended to always use a positive value for N, as this avoids ambiguities with respect to the interpretation of subterm as nested array or array element. With a value of 0 the original array is returned unchanged.

The elements in the Flat array are in the same order as they would be encountered in a depth-first left-to-right traversal of Array.

In the top N levels of Array, terms with functor []/M are interpreted as arrays, in particular [] is interpreted as an empty array and thus eliminated.

Modes and Determinism

Exceptions

(4) instantiation fault
N or Array is a variable
(5) type error
N is not an integer
(5) type error
Array is not an array
(6) out of range
N is less than -1
(24) number expected
N is not an integer, but possibly an arithmetic expression

Examples

?- array_flat(0, []([](a,b,c),[](d,e,f)), A).      % no change
A = []([](a, b, c), [](d, e, f))

?- array_flat(1, []([](a,b,c),[](d,e,f)), A).      % 2-D to 1-D
A = [](a, b, c, d, e, f)

?- array_flat(2, []([](a,b,c),[](d,e,f)), A).      % still 2-D to 1-D
A = [](a, b, c, d, e, f)

?- dim(M, [2,2,2]), array_flat(2, M, A).           % 3-D to 1-D
M = []([]([](_368,_369), [](_365,_366)), []([](_359,_360), [](_356,_357)))
A = [](_368, _369, _365, _366, _359, _360, _356, _357)

?- dim(M, [2,2,2]), array_flat(1, M, A).           % 3-D to 2-D
M = []([]([](_368,_369), [](_365,_366)), []([](_359,_360), [](_356,_357)))
A = []([](_368,_369), [](_365,_366), [](_359,_360), [](_356,_357))

% mixed-dimensional 3-D to 2-D
?- array_flat(1, [](a, [](b), []([](c)), [], d), A).
A = [](a, b, [](c) ,d).

?- array_flat(1, []([],[]), A).                     % empty arrays
A = []

See Also

dim / 2, subscript / 3, array_concat / 3, is_array / 1, array_list / 2, arg / 3