如何在序言中附加列表列表 [英] How to append a list of lists in prolog
问题描述
我想添加一个列表列表,如下所示:append(Ls,L)
,L的第一个元素是Ls中第一个列表的第一个元素,L的第二个元素是Ls中第二个列表的第一个元素,对于Ls中的所有列表,依此类推.此后,L的下一个元素是Ls中第一个列表的第二个元素,依此类推,直到从Ls中的所有列表中取出两个元素.之后,进入Ls中所有列表的第三个元素,依此类推,直到Ls中所有列表的所有元素都包含在L中.
I want to append a list of list like this : append(Ls,L)
,the first element of L is the first element of the first list in Ls,the second element of L is the first element of the second list in Ls, and so on for all the lists in Ls. After this, the next element of L is the second element of the first list in Ls, and so on, until two elements have been taken from all the lists in Ls. After this, come the third elements of all the lists in Ls, and so on, until all the elements of all the lists in Ls are included in L.
例如:
我有一个清单Ls=[[a,b],[c,d],[e,f]]
并想要得到这个L=[a,c,e,b,d,f]
或者我有Ls=[[1,2,3],[4,5,6]]
并且我想获得L=[1,4,2,5,3,6]
forexample:
I have a list Ls=[[a,b],[c,d],[e,f]]
and want to get this L=[a,c,e,b,d,f]
or I have Ls=[[1,2,3],[4,5,6]]
and I want to get L=[1,4,2,5,3,6]
推荐答案
If you want to practise implementing recursive predicates, you could proceed like this using dcg:
matrix_transposed_items(Mss,Xs) :-
notlonger_than(Mss,Xs),
phrase(matrix_tconcat(Mss),Xs).
matrix_tconcat([]) --> [].
matrix_tconcat([Cs|Css]) -->
row_rows_rest_(Cs,Css,Mss),
matrix_tconcat(Mss).
row_rows_rest_([],Css,[]) -->
{ emptylists(Css) }.
row_rows_rest_([X|Xs],Xss,[Xs|Mss]) -->
[X],
nonemptyrows_rest(Xss,Mss).
nonemptyrows_rest([],[]) --> [].
nonemptyrows_rest([[X|Xs]|Xss],[Xs|Mss]) -->
[X],
nonemptyrows_rest(Xss,Mss).
以上代码基于三个辅助谓词,可以这样定义:
Above code is based on three auxiliary predicates which can be defined like this:
nil_or_cons([]).
nil_or_cons([_|_]).
notlonger_than([],Bs) :-
nil_or_cons(Bs).
notlonger_than([_|As],[_|Bs]) :-
notlonger_than(As,Bs).
emptylists([]).
emptylists([[]|Xs]) :-
emptylists(Xs).
让我们运行一些查询!首先,我们使用一些二次矩阵:
Let's run some queries! First, we use some quadratic matrix:
?- matrix_transposed_items([[1,2,3],[4,5,6],[7,8,9]],Xs).
Xs = [1,4,7,2,5,8,3,6,9]. % succeeds deterministically
接下来,OP提供的非二次用例:
Next, the non-quadratic use-cases the OP gave:
?- matrix_transposed_items([[a,b],[c,d],[e,f]],Ls).
Ls = [a,c,e,b,d,f]. % succeeds deterministically
?- matrix_transposed_items([[1,2,3],[4,5,6]],Ls).
Ls = [1,4,2,5,3,6]. % succeeds deterministically
我们也尝试去其他方向"!
Let's try going the "other direction", too!
?- matrix_transposed_items(Mss,[1,2,3,4,5,6,7,8,9,10]).
Mss = [[1,2,3,4,5,6,7,8,9,10]]
; Mss = [[1,3,5,7,9],[2,4,6,8,10]]
; Mss = [[1,6],[2,7],[3,8],[4,9],[5,10]]
; Mss = [[1],[2],[3],[4],[5],[6],[7],[8],[9],[10]]
; false. % terminates universally
这篇关于如何在序言中附加列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!