[ library(lists) | The ECLiPSe Libraries | 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
Ground 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(List, Flat, []).

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

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.

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



See Also

sort / 2, sort / 4, length / 2, member / 2