I'm having a problem where my answer for every Prolog problem I'm posed ends up with the answer list being reversed. It's because I was shown how to use an accumulator to reverse a list, and now the only way I seem to be able to solve a problem is to use a similar program, which gives the answer, but also reverses the list.
For example, when asked to write a program which replaces all instances of the second argument inside the first argument with the third argument, and gives the resulting list as it's fourth argument, I wrote this code:
replace(L, A, B, X):-
accrep(L, [], A, B, X).
accrep([H | T], Y, A, B, X):-
H = A,
accrep(T, [B | Y], A, B, X).
accrep([H | T], Y, A, B, X):-
H \= A,
accrep(T, [H | Y], A, B, X).
accrep([], X, _, _, X).
This does indeed technically solve the problem, but also reverses the list, which wasn't asked for, and I doubt anyone would be impressed when I hand them the correct answer backwards. But I can't think of a way to avert this, and it seems ridiculous to add in code that unreverses the list, when I should never have reversed it in the first place.
Can anyone tell me how to use accumulators without running into this problem? I've had the same issue with multiple other simple programs too.
Thanks, Alex.