title: Replace a single occurrence of an element in a list in Prolog
body: <p>I am given a list, an element to be replaced and the replacement for that element. I managed to do it for all occurrences of the element in that list:  </p>
  
  <pre><code>replace([],X,Y,[]).
  replace([X|T], X, Y, Z) :-
     replace(T, X, Y, Z1),
     Z = [Y|Z1].
  replace([H|T], X, Y, [H|Z]) :-
     replace(T, X, Y, Z). 
  </code></pre>
  
  <p>However now I must only replace the first occurrence of that element.
  My thought process writing: </p>
  
  <pre><code>replace([X|T], X, Y, Z) :-
     replace(T, X, Y, Z1), 
     Z = [Y|Z1].
  </code></pre>
  
  <p>was:<br>
   <code>Z</code> is the result of <code>[X|T],X,Y</code> if <code>Z1</code> is the result of <code>T</code>,<code>XY</code> and <code>Z = [Y|Z1]</code>. Following the same thought process I tried writing the function that only replaces the first occurrence of the element like so:</p>
  
  <p>An idea for implementing only the first occurrence would be from a <code>replace/4</code> to go in a <code>replace/5</code> where I count if I replaced or not like so:</p>
  
  <pre><code>replace_single(L,X,Y,Z) :- 
     replace2(L,X,Y,0,Z).
  
  replace2([],X,Y,C,[]).
  replace2([X|T], X, Y, C, Z) :-
     \+ (C = 0),
     replace2(T, X, Y, C, Z1),
     Z = [X|Z1],
     C is 1.
  replace2([H|T], X, Y, C, [H|Z]) :-
     replace2(T, X, Y, C, Z).
  </code></pre>
  
  <p>Obviously it will not work, I am a little bit lost. Could someone give me a tip or so of how I could think to solve the problem or the solution itself?</p>