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

Asked

Viewed 2,221 times

0

I want to implement a Prolog program that receives an L list, an X numeor and a Y number and insert the X at the top of the list and the Y at the bottom of the list (I wanted a way without using the SWI-Prolog lists module)

1 answer

2

Insert at start is trivial - [X|L]. This creates a list whose head is X and whose tail is L (the original list).

To enter at the end it is necessary to scroll through the entire list, replacing the [] at the end by 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.