title: Prolog - replacing subterms
body: <p>I'm doing some past exam papers for practice for my exam, and I've come across a question that I'm not quite sure how to tackle: </p>
  
  <p><a href="https://i.stack.imgur.com/Z6krv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z6krv.png" alt="enter image description here"></a></p>
  
  <p>I know I've got to use the "univ" function to break up the term into a list, and then recurse through that list and check if any of the elements in the list equal the term we want to replace. However, I'm a bit lost with double recursing when the list contains another complex term that we have to break down further. My attempt so far is as follows:</p>
  
  <pre><code>complexTerm(X) :- nonvar(X), functor(X, _, A), A &gt; 0.
  
  replace(Term, Subterm, Subterm1, Term1) :-
      Term =.. [H|T],
      replaceSub([H|T], Subterm, Subterm1, Term1)
  
  replaceSub([], Subterm, Subterm1, Term1).
  replaceSub([H], Subterm, Subterm1, Term1) :- 
      atomic(X),
      H == Subterm, 
      H = Subterm1.
  replaceSub([H], Subterm, Subterm1, Term1) :-
      complexTerm(H),
      replace(H, Subterm, Subterm1, Term1).
  replaceSub([H|T]) :- % not sure where to continue with this.
  </code></pre>
  
  <p>Any pointers would be much appreciated. Note that for the exam we can't use external modules.</p>
  
  <p>Thanks for your time.</p>