I want to implement a prolog program that receives an L list, an X number and a Y number, and insert X at the beginning of the list and Y at the end of the list (I wanted a way without using the SWI-prolog module lists )
I want to implement a prolog program that receives an L list, an X number and a Y number, and insert X at the beginning of the list and Y at the end of the list (I wanted a way without using the SWI-prolog module lists )
Inserting at the beginning is trivial - [X|L]
. This creates a list whose head is X
and whose tail is L
(the original list).
To insert at the end it is necessary to go through the entire list, replacing []
at the end with a unit list with the desired element:
inserir_final([], Y, [Y]). % Se a lista estava vazia, o resultado é [Y]
inserir_final([I|R], Y, [I|R1]) :- % Senão, o primeiro elemento é igual, e o resto é obtido
inserir_final(R, Y, R1). % Inserindo o elemento Y no final do antigo resto