Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog element in lists replacement

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

like image 715
Donald Avatar asked May 01 '11 19:05

Donald


People also ask

How do I update a list in Prolog?

You can express the above in Prolog like so: update([],[],[]). update([[X,_]|Xs],[Y|Ys],[[X,Y]|XYs]) :- update(Xs,Ys,XYs).

How do you check if a list contains a value in Prolog?

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.

How do you get the second element in a list in Prolog?

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.

How do you find the nth element of a list in Prolog?

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 .


1 Answers

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).
like image 119
svick Avatar answered Sep 25 '22 17:09

svick