[ library(lists) | Reference Manual | Alphabetic Index ]

flatten(+NestedList, ?FlatList)

Succeeds if FlatList is the list of all elements in NestedList, as found in a left-to-right, depth-first traversal of NestedList.
+NestedList
A List.
?FlatList
List or variable.

Description

FlatList is the list built from all the non-list elements of NestedList and the flattened sublists. The sequence of elements in FlatList is determined by a left-to-right, depth-first traversal of NestedList.

The definition of this Prolog library predicate is:

flatten(List, Flat) :-
	flatten_aux(List, Flat, []).

flatten_aux([], Res, Cont) :- -?-> !, Res = Cont.
flatten_aux([Head|Tail], Res, Cont) :-
	-?->
	!,
	flatten_aux(Head, Res, Cont1),
	flatten_aux(Tail, Cont1, Cont).
flatten_aux(Term, [Term|Cont], Cont).
This predicate does not perform any type testing functions.

Since ECLiPSe 7.0, arrays are treated like lists, and also flattened.

Modes and Determinism

Fail Conditions

Fails if FlatList does not unify with the flattened version of NestedList.

Resatisfiable

No.

Examples

    Success:
        [eclipse]: flatten([[1,2,[3,4],5],6,[7]], L).
        L = [1, 2, 3, 4, 5, 6, 7]
        yes.

        [eclipse]: flatten([1,2,3], L).
        L = [1, 2, 3]
        yes.

      [eclipse]: flatten(a, L).
      L = [a]
      yes.

    Fail:
        [eclipse]: flatten([1,[3],2], [1,2,3]).
        no.

See Also

flatten / 3, sort / 2, sort / 4, length / 2, member / 2