I have searched for information on the net, regarding how to insert an element in the middle of a list in Prolog, but I have not found relevant information regarding what I want to do.
%Create_a_program_in_Prolog_that_inserts_an_element_in_the_half_of_a_list %insert_half([a,b,c,d,e,f],x,R). %R=[a,b,c,x,d,e,f].
I am new to using the Prolog program and learning its logic. Also, I'm honest, it's a university exercise and I don't know how to do it, thanks in advance
To insert in the middle of a list you can traverse the list at two "speeds": one advancing one element at a time and the other advancing two elements at a time.
This way when you get to the end of the second list the first will be in the middle. At that point you can add the item you want in the middle along with the other half of the list.
The second clause of insert_half/4 covers the case of lists of odd number. If the procedure is removed it will only happen for lists of even number of elements.
Test cases:
To avoid leaving alternatives, another auxiliary procedure can be added to help indexing:
In which we now see that the second example leaves no alternatives: