Question: Question 3 : ( 2 0 points for each case ) Write a predicate replacelast / 4 that substitutes the first argument x with the

Question 3: (20 points for each case)
Write a predicate replacelast/4 that substitutes the first argument x with the second argument Y for the last element, an occurrence of x in a list of elements. If the list is empty the result is the empty list. If x is not in the list, then the result is the list itself.
hint: the last occurrent is represented by when the tail is empty : [?xI[]]
Three cases
The list is empty, then the result is empty
x matches the head, insert Y in the new list and replace x with Y.
x does not match the head and the tail is the empty list head, replace x with Y in the tail
?- replacelast(a,z,[a,b,c,a,r,a,z],R).
R=[a,b,c,a,r,a,z].
?- replacelast(a,z,[a,b,c,a,r,a,y],R).
R=[a,b,c,a,r,a,y].
?- replacelast (1,6,[5,0,1,1,1,5,1],R).
R=[5,0,1,1,1,5,6].
?- replacelast(a,z,[a,b,c,a,r,a], R).
R=[a,b,c,a,r,z].
Question 3 : ( 2 0 points for each case ) Write a

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Accounting Questions!