Recursively insert an element into a list
I want to write a Prolog program to insert a list in another list. For example:
% insert [1, 2] to [[1, 3, 4], [2, 5]]
[[1, 3, 4], [2, 5], [1, 2]]
I wrote the following:
insertList([X], [], [[X]]).
insertList([H|T], [H2|T2], [[H|T], H2|T2]).
But this approach adds one list only, because there is no recursion. How can I make the recursion in this case? I had the same problem while inserting elements to a list in this code:
in开发者_开发百科sert(X, [], [X]).
insert(X, [H|T], [X,H|T]).
So, how do I make a recursion to inserting the list? The insertion can be either in the beginning, or in the end of the list.
Evidently what you want is to insert an item at the end of a list. The fact that the item being inserted is a list does not make a critical difference here.
insertAtEnd(X,[ ],[X]).
insertAtEnd(X,[H|T],[H|Z]) :- insertAtEnd(X,T,Z).
If you wanted instead to insert at the beginning, no recursion is needed! In fact you don't even need a predicate to do this since the Prolog term [X|L]
"inserts" the item X at the beginning of list L.
Perhaps you have in mind a more difficult problem, namely inserting an item into a sorted list in a proper way to maintain the sorted order. However there's not much in the Question to suggest that this is your problem.
Probably best to look at the following post where the first answer contains a link to a site with explanation of recursion in prolog. It's a good starting point to get the hang of the mentioned problems.
精彩评论