簡體   English   中英

列表內的升序序數列表

[英]Prolog lists of ascending number inside a list

我在開始時有一個[1,2,3,1,0]列表,但需要將其拆分為多個子列表,新列表變為[[1,2,3],[1],[0] ]。

我在序言中了解的基本概念是通過比較數字。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM