Inserting X in its correct position in a sorted li

2019-05-26 22:26发布

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

标签: prolog
1条回答
Viruses.
2楼-- · 2019-05-26 23:00

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).
查看更多
登录 后发表回答