1

I want to replace b,c with x,y,z in a list in Prolog. I have a list [a,b,c,d,e,f] and result will be [a,x,y,z,d,e,f]. How can I write this in Prolog?

replace([],_,[]).
replace([x|T1],Var,[Y|T2]):-
      member(X=Y,var),
      !
   ;  X=Y
   ),
   replace(T1,Var,T2).

-? replace([a,b,c,d,e,f],[b,c=x,y,z],R).
Will Ness
  • 70,110
  • 9
  • 98
  • 181
  • 1
    You have typographical errors in your program. Also, try `write_canonical([b,c=x,y,z])`. Prolog doesn't see this term the way you think it does. Written in list notation, it's treated as: `[b, =(c,x), y, z]`. What if `b,c` occurs more than once in your list? Do all occurrences need to be replaced? – lurker Dec 14 '17 at 11:52
  • Here's a hint: think about how you can use `append/3 to` determine whether a list `P` is the prefix of list `L`. – lurker Dec 14 '17 at 15:55
  • your query should be `replace([a,b,c,d,e,f], [b,c], [x,y,z], R).` It is you the programmer which assigns the meaning to this predicate's arguments. – Will Ness Dec 14 '17 at 17:13

1 Answers1

0

This is essentially equivalent to the problem of replacing substrings in Prolog. Using the replace_substring/4 predicate, you can replace a subsequence of the list in this way:

:- initialization(main).
:- set_prolog_flag(double_quotes, chars). 

main :-
    replace_substring([a,b,c,d,e,f],[b,c],[x,y,z],Result),
    writeln(Result).

replace_substring(String, To_Replace, Replace_With, Result) :-
    append([Front, To_Replace, Back], String),
    append([Front, Replace_With, Back], Result).

This program prints [a,x,y,z,d,e,f].

Anderson Green
  • 30,230
  • 67
  • 195
  • 328