Hi i was wondering if you could help me out with this
From programming in Prolog: write Prolog script for replacement any given element in lists by an another given element. For example:
replace( 3, a,[1,2,3,4,3,5], [1,2,a,4,a,5])=true
Many Thanks in advance
You can express the above in Prolog like so: update([],[],[]). update([[X,_]|Xs],[Y|Ys],[[X,Y]|XYs]) :- update(Xs,Ys,XYs).
If you want to check if a list contains a member, use memberchk/2 . so memberchk(I/J, Item) succeeds if I/J is in the list Item . Your include/3 predicate has no base case, and attempt to ensure that every element of the given list is I/J , so it will always fail.
You can move unification into the head of the clause and simply write: second([_, Second| _], Second). The notation for lists is to write the initial elements separated by commas and then a vertical bar to separate the list tail, i.e. the list containing the rest of the elements.
match([Elem|Tail],Num,Num,Elem). match([Elem|Tail],Num,C,MatchedNumber):- match(Tail,Num,N,Elem), C is N+1. In the first line I say, if the requested element number is equal to counter, then give the first element of the current list to the variable called MatchedNumber .
In Prolog, most list processing is done by processing the head and then recursively processing the rest of the list. Of course, you can't forget about the base case, which is an empty list.
Replacing anything with anything in an empty list results again in an empty list. If the head of the list is the same as the element to replace, replace it, otherwise, keep it as it is. In both cases, process recursively the rest of the list. Translated from English into Prolog:
replace(_, _, [], []).
replace(O, R, [O|T], [R|T2]) :- replace(O, R, T, T2).
replace(O, R, [H|T], [H|T2]) :- H \= O, replace(O, R, T, T2).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With