在Prolog中压缩列表列表

时间:2015-06-16 23:37:54

标签: list prolog flatten dcg

我有这个列表清单:

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

我想使用 Prolog 编写一个函数,使其变得像这样:

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

有什么建议吗? 谢谢。

2 个答案:

答案 0 :(得分:0)

使用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]].

如果需要,您应该查看at the implementation by SWI-Prolog并复制它。如果必须在GNU-Prolog中执行此操作,请忽略must_be/2

但是如果因为findall/3而需要这个,请记住可能还有findall/4可用(不适用于GNU-Prolog,但SWI-Prolog有):

$ 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].

使用差异列表几乎可以避免您需要展平列表的所有情况。

答案 1 :(得分:0)

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).