Write a Prolog program called replace that replaces all occurrences of one item in a list with a new item. Example under:
?- replace([apple,butter,apple,candy,apple,potato],apple,milk,Result).
Result = [milk,butter,milk,candy,milk,potato]
PREDICATE IN PROLOG:
replace([], _, _, []). %base case for empty list
%recursive cases
%when first element of list is to be replaced, we replace it and
recurse for rest of list
replace([X1|Y1], X1, X2, [X2|Y2]):- replace(Y1, X1, X2, Y2),
!.
%when first element of list is not to be replaced, we keep it and
recurse for rest of list
replace([X|Y1], X1, X2, [X|Y2]):- replace(Y1, X1, X2, Y2).
OUTPUT:
Regards!
Get Answers For Free
Most questions answered within 1 hours.