flatten a list of lists in Prolog

2.2k views Asked by At

I have this list of lists:

 L = [[[a,b],[d,e]],[[m,f],[p,o]],[[r,l],[v,d]]].

I want to write a function using Prolog that flattens it in a way that it becomes like this :

 L = [[a,b],[c,d],[m,f],[p,o],[r,l],[v,d]].

Any suggestions? Thank you.

2

There are 2 answers

4
AudioBubble On

Using the predicate append/2:

?- L = [[[a,b],[d,e]],[[m,f],[p,o]],[[r,l],[v,d]]], append(L, R).
L = [[[a, b], [d, e]], [[m, f], [p, o]], [[r, l], [v, d]]],
R = [[a, b], [d, e], [m, f], [p, o], [r, l], [v, d]].

You should look at the implementation by SWI-Prolog and copy it if you need to. Leave out the must_be/2 if you must do it in GNU-Prolog.

But if you need this because of findall/3, keep in mind that there might also be a findall/4 available (not for GNU-Prolog, but SWI-Prolog has it):

$ swipl
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 7.3.2-25-gf8c39d8)
Copyright (c) 1990-2015 University of Amsterdam, VU Amsterdam
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.

For help, use ?- help(Topic). or ?- apropos(Word).

?- findall(X, between(1,3,X), Xs, Rest), findall(Y, between(7,11,Y), Rest).
Xs = [1, 2, 3, 7, 8, 9, 10, 11],
Rest = [7, 8, 9, 10, 11].

Almost every situation where you need to flatten a list could be avoided using difference lists.

0
Zineb SLAM On
possible_moves(Tray,PossibleMoves):-
    findall([J,1,X,Y],possible_move(Tray,[J,1,X,Y]),T1),
    findall([J,2,X,Y],possible_move(Tray,[J,2,X,Y]),T2),
    append(T1,T2,Res),
    findall([J,3,X,Y],possible_move(Tray,[J,3,X,Y]),T3),
    append(Res,T3,PossibleMoves).