2
votes

I am trying to write two predicates. They are to replace the second or second last element of a list with a given input element. So far I have only been able to replace the first element of a list or insert at position two. I am very new to Prolog and I am having some difficulties understanding the backtracking and recursion. Could anyone help me with this? The more detail in answer the better as I really want to understand.

I call like this: repl([1,2,3,4,5], new, Y). and I am trying to get the result Y = [1,new,3,4,5] back. I am also trying to do the same to replace the second last one, like this: repl2([1,2,3,4,5], new, Y). which i want to return Y = [1,2,3,new,5].

So far what i have tried is

repl([_], X, [X]).
repl([H|T], X, [H,X|T]) 

I know this is very wrong for many reasons. I have tried many different things but as I mentioned this syntax and this backtracking and recursion is a bit mind boggling to say the least.

1
What do you expect when the list is empty or has one element ? e.g repl([],new,Y) should succeed or fail?? - coder
I was able to figure out the first one. repl([H,X|T], A, [H,A|T]). This works for me. And returns false if list is 0 or 1 elements. Is that correct? Or should i have a case for empty list as well always? I want it to return false always if list is empty or has one element - Jens B
Since you want to return false in case of 0,1 length of lists then it's fine. I'll give an answer for second one if you find it difficult...? - coder

1 Answers

1
votes

As you already figure it out, for the repl/3 predicate the definition is:

repl([H,_|T], A, [H,A|T]). 

In the above definition watch the underscore (in your definition you had a variable X, use underscore to mute the singleton warning).

For the repl2/3 definition you could write:

repl2(L, A, OutL):-reverse(L, [H,_|T]), reverse([H,A|T], OutL).

Example:

?- repl2([1,2,3,4,5], new, Y).
Y = [1, 2, 3, new, 5].