[英]flatten a list of lists in Prolog
我有這個列表清單:
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]].
有什么建議么? 謝謝。
使用謂詞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]].
您應該查看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].
幾乎所有需要壓縮列表的情況都可以使用差異列表來避免。
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).
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.