我开始使用prolog几个星期了,然而我却更深入地看到了操纵列表的递归谓词的构造。我的问题是:它可以构建一个谓词,在给定数量的其他列表中拆分给定列表吗?
例如,我想象的那样:
split([H|T], NumberLists, Lists)
- 递归实现 -
?- split([1,2,3,4,5,6,7,8],2,Lists).
Lists = [[1,2,3,4],[5,6,7,8]].
?- split([1,2,3,4,5,6,7,8],4,Lists).
Lists = [[1,2],[3,4],[5,6],[7,8]].
有人能给我一个实施的例子吗?
谢谢!
答案 0 :(得分:1)
这样的事应该做。没有内置谓词:
partition( [] , _ , [] ) . % the empty list is already partitioned
partition( Xs , N , [Pfx|Ys] ) :- % for a non-empty list, we...
take(N,Xs, Pfx , Sfx ) , % - split it into a prefix of (at most) length N and its suffix.
partition(Sfx,N,Ys) % - recursively partition the suffix
. % Easy!
take( 0 , Xs , [] , Xs ) . % if we reach zero, we're done. Close the prefix and hand back whatever is left over.
take( N , [] , [] , [] ) :- % if we exhaust the source list, we're done. close the prefix and hand back the empty list as the suffix.
N > 0 % - assuming, of course, that N is greater than zero.
. %
take( N , [X|Xs] , [X|Ys] , Sfx ) :- % otherwise prepend the current item to the prefix
N > 0 , % - assuming N is greater than zero,
N1 is N-1 , % - then decrement N
take(N1,Xs,Ys,Sfx) % - and recurse down.
. % Also easy!