Search code examples
prolog

How to make the predicate to replace the last occurrence of the given element in the list with the specified new value?


Can you help me, I can't figure out how to do this: the replace_last predicate to replace the last occurrence of a given element in the list with the specified new value

replace_last(InList, OutList) :-
   append([[First], Middle, [Last]], InList),
   append([[Last], Middle, [First]], OutList).

Solution

  • I would use negation:

    replace_last(Input,Find,Replace,Output) :-
        append(X,[Find|Y],Input),
        \+ memberchk(Find,Y),
        append(X,[Replace|Y],Output).