2015-03-30 47 views
0

这样的列表是谓语:分区在序言

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

我该如何解决这个问题?谢谢!

+1

你需要进一步指定你想要的。你的定义显示*所有*可能的分区 - 包括你的! – false 2015-03-30 22:02:46

+1

我明白了!感谢您的帮助! PARTLIST(LEN,[],[])。 (H,Len),append(H,LT,L),partList(Len,LT,T)。 – qing78 2015-03-31 00:04:23

回答

2

最简单的方法就是看问题是从列表头部反复剥离第N个项目(直到列表被耗尽)。

partition([]  , []  ) . % if the source list is exhausted, we're done. 
partition([X]  , [X]  ) . % if the source list contains just one item, we're done. 
partition([X,Y|Z] , [[X,Y]|R]) :- % if the source list contains 2 or more items, we take the 1st two, and ... 
    partition(Z,R)      % - recursively partition the remainder. 
    .         % Easy!. 

使其通用并不复杂得多。

首先,我们需要一种方法来列表划分为前缀,含N项(或更少如果列表不够长)和后缀,含有任何剩下的(这可能是什么) :

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!