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.
repl([],new,Y)should succeed or fail?? - coderrepl([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