Prolog lists of ascending number inside a list

2019-08-11 17:26发布

I Have a list of [1,2,3,1,0] at start but need to split it into a number of sub lists where the new lists becomes [[1,2,3],[1],[0]].

The basic concept that I know in prolog is by comparing numbers.

    ascending([Head | [HeadTail|TailTail]]) :- Head =< HeadTail.

标签: list prolog
2条回答
ら.Afraid
2楼-- · 2019-08-11 17:51

we can do with basic list' pattern matching

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

test:

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.
查看更多
ゆ 、 Hurt°
3楼-- · 2019-08-11 17:57
% 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 ).
查看更多
登录 后发表回答