Prolog element in replacing lists

Hi, I was wondering if you can help me with this.

From programming in Prolog: write a Prolog script to replace any given element in lists with another given element. For instance:

replace( 3, a,[1,2,3,4,3,5], [1,2,a,4,a,5])=true

Thank you very much in advance

+5
source share
5 answers

In Prolog, most of the list processing is done by head processing and then recursively processes the rest of the list. Of course, you cannot forget about the base case, which is an empty list.

- - . , , . . :

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).
+11

, , . :

?- replace(3,three,[1,2,3],Xs).
Xs = [1,2,three] ;                 % OK: correct
false

?- A=3, replace(A,B,[1,2,3],Xs).   % OK: correct
Xs = [1,2,B], A = 3 ;
false

! :

?- replace(A,B,[1,2,3],Xs).        % FAIL: should succeed more than once...
Xs = [B,2,3], A = 1 ;              %       ... but the other solutions are missing 
false

?- replace(A,B,[1,2,3],Xs), A=3.   % FAIL: this query _should_ succeed ...
false                              %       ... it does not!

? - (!)/0 (\=)/2, , .

, - "", ! , Prolog dif/2 (\=)/2. :

% code by @svick, modified to use dif/2 instead of (\=)/2
replaceP(_, _, [], []).
replaceP(O, R, [O|T], [R|T2]) :- replaceP(O, R, T, T2).
replaceP(O, R, [H|T], [H|T2]) :- dif(H,O), replaceP(O, R, T, T2).

, replaceP/4:

?- replaceP(3,three,[1,2,3],Xs).
Xs = [1,2,three] ;                 % OK: correct, like before
false

?- replaceP(A,B,[1,2,3],Xs).       % OK: four solutions, not just one
Xs = [B,2,3], A = 1 ;         
Xs = [1,B,3], A = 2 ;
Xs = [1,2,B], A = 3 ;
Xs = [1,2,3], dif(A,1),dif(A,2),dif(A,3) ;
false

?- replaceP(A,B,[1,2,3],Xs), A=3.  % OK (succeeds now)
Xs = [1,2,B], A = 3 ;                 
false
?- A=3, replaceP(A,B,[1,2,3],Xs).  % OK (same as before)
Xs = [1,2,B], A = 3 ;
false
+5
replace(_, _ , [], []).

replace(X, Y, [ X | Z ], [ Y | ZZ]):- ! , replace( X, Y, Z, ZZ).

replace(X, Y, [ W | Z], [ W | ZZ] :- replace(X, Y, Z, ZZ). 

Although, as a rule, it usually follows that 3. arg be the first. And, strictly speaking, the above does not replace anything in the list, it just means that the 4th argument is similar to the one in the third, but with Y 'instead of X'.

0
source
replace(E,S,[],[]).
replace(E,S,[E|T1],[S|T2]):-replace(E,S,T1,T2).
replace(E,S,[H|T1],[H|T2]):-E\=H, replace(E,S,T1,T2).

the idea is simple, if the elements match, change it, if not, go to empty.

0
source
domains
I=integer*
K=integer*
Z=integer
A=integer
predicates
nondeterm  rep(I,Z,A,K)
clauses
rep([],_,_,[]).
rep([Z|T1],Z,A,[A|T2]):- rep(T1,Z,A,T2).
rep([H|T1],Z,A,[H|T2]) :- rep(T1,Z,A,T2).
goal
rep([1,2,3],2,4,X).
0
source

All Articles