title: Prolog: Replace an atom by other atom in compound terms
body: <p>I am trying to write a simple prolog program which should replace an atom by another atom. The program can take complex functor as an input and would replace all the atoms by another atoms.</p>
  
  <p>e.g. In the below term, I want to replace atom a by ax only where I encounter a leaf (i.e. not a functor name).</p>
  
  <pre><code>replace(put(a,table,aside(a(dont,replace),a)),X).
  </code></pre>
  
  <p>which should produce output,</p>
  
  <pre><code>X = put(ax,table,aside(a(dont,replace),ax));
  false.
  </code></pre>
  
  <p>In the above output, replaced a with ax everywhere except the functor name. In a way all the leaves are replaced. But not internal nodes.</p>
  
  <p>I have tried following,</p>
  
  <pre><code>replace([],[]).
  replace([H | T], [H1 | T1]):-
          (
          atom(H), (H == a)  %If it's an atom and equal to a, then replace H1 with ax.
          -&gt; H1 = ax, replace(T, T1)  %and recursively follow the same for T.
          ; H1 = H, T1 = T, replace(T, T1)  %else keep things as it is and recurse.
          ).
  replace(L, R):-
          functor(L, F1, A1),    %if it's a functor then don't do anything, just follow
          functor(R, F1, A1),    %for the args of the functor.
          L =.. [F1 | Args1],
          R =.. [F1 | Args2],
  
          replace(Args1, Args2),!.
  </code></pre>
  
  <p>Problem 1. I receive shallow output for the same input </p>
  
  <pre><code>replace(put(a,table,aside(ad,a,toe)),X).
  X = put(ax,table,aside(ad,a,toe)).
  </code></pre>
  
  <p>Problem 2. My predicate would fail when arity of the functor changes. For example,</p>
  
  <pre><code>replace(put(a,table,aside(a(dont,replace),a)),X).
  Undefined predicate: substit/2
  </code></pre>
  
  <p>I realize my approach might not be the best one.
  Can someone please help me either fix the issues or suggest a new approach.</p>
  
  <p>Thanks.</p>