substitute in a nested list (prolog)

Posted by linda on Stack Overflow See other posts from Stack Overflow or by linda
Published on 2009-11-20T15:03:30Z Indexed on 2010/04/17 22:03 UTC
Read the original article Hit count: 308

Filed under:
|
|

/* substitute(X,Y,Xs,Ys) is true if the list Ys is the result of substituting Y for all occurrences of X in the list Xs.

This is what I have so far:

subs(_,_,[],[]).
subs(X,Y,[X|L1],[Y|L2]):- subs(X,Y,L1,L2).
subs(X,Y,[H|L1],[H|L2]):- X\=H, not(H=[_|_]), subs(X,Y,L1,L2).
subs(X,Y,[H|_],[L2]):- X\=H, H=[_|_], subs(X,Y,H,L2).

My code works except it omits the elements following the nested list. For example:

?- subs(a,b,[a,[a,c],a],Z).
Z = [b, [b, c]] .

What should I add to this program?

© Stack Overflow or respective owner

Related posts about swi-prolog

Related posts about prolog