Inserting X in its correct position in a sorted li

2019-05-26 22:13发布

问题:

In prolog how do I insert X in its correct position in a sorted list?

My Attempt:

insert(X,[Y|Rest],[X,Y|Rest]):-
X @< Y;
insert(X,Rest,BiggerRest).

回答1:

You're on the right track, but you need to make this three cases.

insert(X, [], [X]).
insert(X, [Y|Rest], [X,Y|Rest]) :-
    X @< Y, !.
insert(X, [Y|Rest0], [Y|Rest]) :-
    insert(X, Rest0, Rest).


标签: prolog