0

I am writing a function replaceFirst(X Y L) which replaces only the first occurrence of X with Y in the list L.

Here is what I have done so far:

(define replaceFirst( lambda (X Y L)
    (cond
        ( (null? L)             '() )
        ( (equal? (car L) X)    (set! Y (cdr L)) )
        ( #t                    (replaceFirst X Y (cdr L)) )
    )
))

which gives an error of In procedure setter: Wrong type argument in position 1: #<procedure car (_)>

EDIT

I have come up with a solution:

Firstly, if X is the first element, instead of using set! (which I am unfamiliar with), I cons Y to the list excluding X.

Otherwise, I cons the first element of the list with the function called recursively on the rest of the list.

(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))) )
    )
))
KOB
  • 4,084
  • 9
  • 44
  • 88

1 Answers1

0

In you clause:

( (equal? (car L) X)    (set! Y (cdr L)) )

What does the function actually return? And if Y is supposed to be the replacement for X, once you know that (car L) is equal to X, what would setting the value of the variable Y to be the rest of the list do for you?

Your update is fine, but do note that it returns a new list like L, but in which the first occurrence of X has been replaced by Y. It's not the same list. That's probably fine, but the use of set! in your first attempt suggests that maybe you wanted to modify the list that was passed in as input.

Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
  • It doesn't matter that it's a new list. Looking back on my first solution I see how poor it was! I am now attempting to write a function that replaces the LAST occurrence of X with Y in L, which is far more difficult. Any hints on where to get started would be much appreciated. – KOB Mar 31 '16 at 14:24
  • @KOB one easy solution would just be `(define (replace-last x y lst) (reverse (replace-first x y (reverse lst))))`. – Joshua Taylor Mar 31 '16 at 14:44