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))) )
)
))