title: Replacing the first occurence of an element in a list
body: <p>I am writing a function <code>replaceFirst(X Y L)</code> which replaces only the first occurrence of X with Y in the list L.</p>
  
  <p>Here is what I have done so far:</p>
  
  <pre><code>(define replaceFirst( lambda (X Y L)
      (cond
          ( (null? L)             '() )
          ( (equal? (car L) X)    (set! Y (cdr L)) )
          ( #t                    (replaceFirst X Y (cdr L)) )
      )
  ))
  </code></pre>
  
  <p>which gives an error of <code>In procedure setter: Wrong type argument in position 1: #&lt;procedure car (_)&gt;</code></p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I have come up with a solution: </p>
  
  <p>Firstly, if <code>X</code> is the first element, instead of using <code>set!</code> (which I am unfamiliar with), I <code>cons</code> <code>Y</code> to the list excluding <code>X</code>. </p>
  
  <p>Otherwise, I <code>cons</code> the first element of the list with the function called recursively on the rest of the list.</p>
  
  <pre><code>(define replaceFirst( lambda (X Y L)
      (cond
          ( (null? L)             '() )
          ( (equal? (car L) X)    (cons Y (cdr L)) )
          ( #t                    (cons (car L) (replaceFirst X Y (cdr L))) )
      )
  ))
  </code></pre>