在Prolog中对列表进行分区
这是谓词:在Prolog中对列表进行分区,prolog,Prolog,这是谓词: partList(Len,L,R):- length(L,LL), length(R,RR), RR is LL/Len, append(R,L). 查询显示: 42 ?- partList(2,[t,t,t,f,f,t,f,f],R). R = [[], [], [], [t, t, t, f, f, t, f, f]] . 但我想分成两部分 [[t,t],[t,f],[f,t],[f,f]]. 我该如何解决这个问题?谢谢 最简单的方法是查看
partList(Len,L,R):-
length(L,LL),
length(R,RR),
RR is LL/Len,
append(R,L).
查询显示:
42 ?- partList(2,[t,t,t,f,f,t,f,f],R).
R = [[], [], [], [t, t, t, f, f, t, f, f]] .
但我想分成两部分
[[t,t],[t,f],[f,t],[f,f]].
我该如何解决这个问题?谢谢 最简单的方法是查看问题,即反复从列表的开头剥离前N项(直到列表用尽) 使其通用化并不复杂 首先,我们需要一种方法将列表划分为一个前缀,包含N个项目(如果列表不够长,则更少)和一个后缀,其中包含剩余的内容(可能什么都没有): 这是问题的症结所在。一旦有了它,就只需反复(递归)应用它,直到找到空列表:
partition( _ , [] , [] ) . % if the source list is empty, we're done.
partition( N , L , [P|R] ) :- % otherwise...
take_prefix(N,L,P,S) , % - break it up into a prefix and a suffix,
partition(N,S,R) % - and recurse down on the suffix.
. % Easy!
您需要进一步指定所需的内容。您的定义显示了所有可能的分区-包括您的分区!我明白了!谢谢你的帮助!零件列表(Len、[]、[])。零件列表(Len,L,[H | T]):-length(H,Len),append(H,LT,L),零件列表(Len,LT,T)。
take_prefix( _ , [] , [] , [] ) . % if the source list is empty, both prefix and suffix are empty, regardless of the value of N.
take_prefix( 0 , [X|Xs] , [] , [X|Xs] ) . % if N is 0, The prefix is the empty list and the suffix is the source list.
take_prefix( N , [X|Xs] , [X|P] , S ) :- % otherwise, add the head to the prefix,
N > 0 , % - assuming N > 0
N1 is N-1 , % - decrement N
take_prefix(N1,Xs,P,S) % - and recurse down.
. % Easy!
partition( _ , [] , [] ) . % if the source list is empty, we're done.
partition( N , L , [P|R] ) :- % otherwise...
take_prefix(N,L,P,S) , % - break it up into a prefix and a suffix,
partition(N,S,R) % - and recurse down on the suffix.
. % Easy!