-1

How can I flatten a list in Prolog, for example:


    from A = [["a","b"],["c"]]
    to B = ["a", "b", "c"] ?
Lucian Green
  • 182
  • 6

1 Answers1

-2

A list can be flattened using maplist and append, in the following way.

A two-level list may be flattened as shown.


    ?- A=[["a","b"],["c"]],maplist(append,[A],[B]).
    A = [["a", "b"], ["c"]],
    B = ["a", "b", "c"].

A three-level may be flattened with two passes of the command.


    ?- A=[[["a","b"]],[["c"]]],maplist(append,[A],[B]),maplist(append,[B],[C]).
    A = [[["a", "b"]], [["c"]]],
    B = [["a", "b"], ["c"]],
    C = ["a", "b", "c"].

Mixtures of two and three levels in a list results in an error from two passes of the command.


    ?- A=[[["a","b"]],[["c"]],["d"]],maplist(append,[A],[B]),maplist(append,[B],[C]).
    false.

Mixtures of two and three levels in a list can only be partially flattened with one pass of the command.


    ?- A=[[["a","b"]],[["c"]],["d"]],maplist(append,[A],[B]).
    A = [[["a", "b"]], [["c"]], ["d"]],
    B = [["a", "b"], ["c"], "d"].
Lucian Green
  • 182
  • 6
  • 2
    That is not flattening **a** list, but flattening a very specific list. – false Nov 13 '21 at 10:51
  • It is a terrible answer but since you have answered it yourself I am wondering if you really _want_ any help at all. You seem to _need_ help but this is a different topic. – User9213 Nov 13 '21 at 10:56
  • You can also use the custom predicate foldr to partially flatten lists, as follows: foldr(Function,A,L,B):- reverse(A,C),foldl(Function,C,L,B),!. and foldr(append,A,[],B). – Lucian Green Nov 13 '21 at 23:24