我在开始[1,2,3,1,0]的列表,但需要将其拆分成,[1],[0]若干个子名单,其中新列表变为[[1,2,3] ]。
基本概念,我知道在序言中是比较数字。
ascending([Head | [HeadTail|TailTail]]) :- Head =< HeadTail.
我在开始[1,2,3,1,0]的列表,但需要将其拆分成,[1],[0]若干个子名单,其中新列表变为[[1,2,3] ]。
基本概念,我知道在序言中是比较数字。
ascending([Head | [HeadTail|TailTail]]) :- Head =< HeadTail.
我们可以基本清单做”模式匹配
ascending([A], [[A]]).
ascending([A,B|T], R) :-
( A > B -> R = [[A],P|Q] ; P = [M|N], R = [[A,M|N]|Q] ),
ascending([B|T], [P|Q]).
测试:
1 ?- ascending([1,2],X).
X = [[1, 2]] ;
false.
2 ?- ascending([2,1],X).
X = [[2], [1]] ;
false.
3 ?- ascending([1,2,3,1,0],X).
X = [[1, 2, 3], [1], [0]] ;
false.
% Trivial base case
asc([],[]).
% Invoke helper
asc([Ah|Ar],B) :- asc(Ar,[Ah],[],B).
% asc(InputList, CurrentSublistReversed, PreviousSublistsReversed, Result )
% No more input; add unreversed CurrentSublist & unreverse result
asc([],A,C,D) :- reverse(A,Ar), reverse([Ar|C],D).
% Next value gets added to head of current reversed sublist
asc([Ah|Ar],[Bh|Bt],C,D) :- Ah >= Bh, asc( Ar, [Ah,Bh|Bt], C, D).
% Unreverse current sblist, add to head of reversed list of previous sublists; start new sublist
asc([Ah|Ar],[Bh|Bt],C,D) :- Ah < Bh, reverse( [Bh|Bt], Br ), asc( Ar, [Ah], [Br|C], D ).