Insert an element at the beginning and end of a list in prolog

0

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 )

    
asked by anonymous 17.12.2016 / 16:20

1 answer

2

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
    
26.12.2016 / 10:43