up previous next
flatten    --    flatten a list


Syntax
flatten(L: LIST): LIST
flatten(L: LIST, N: INT): LIST

Description
Components of lists may be lists themselves, i.e., lists may be nested. With one argument this function returns the list obtained from the list L by removing all nesting, bringing all elements to the top level. With the optional second argument, N, nesting is removed down N levels.

Thus, the elements of M := flatten(L,1) are formed as follows: go through the elements of L one at a time; if an element is not a list, add it to M; if an element is a list, add all of its elements to M.

Higher levels are recursive: flatten(L, N) = flatten(flatten(L, N-1),1). For N large enough flatten(L, N) gives the same result as flatten(L).

Example
/**/  flatten([1,["a","b",[2,3,4],"c","d"],5,6]);
[1, "a", "b", 2, 3, 4, "c", "d", 5, 6]

/**/  L := [1,2, [3,4], [5, [6,7,[8,9]]]];
/**/  flatten(L,1);
[1, 2, 3, 4, 5, [6, 7, [8, 9]]]

/**/  flatten(It,1);
[1, 2, 3, 4, 5, 6, 7, [8, 9]]

/**/  flatten(L,2);  -- same as flatten(flatten(L,1),1)
[1, 2, 3, 4, 5, 6, 7, [8, 9]]

/**/  flatten(L,3);  -- same as flatten(L)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

See Also