views:

369

answers:

1

Hi!

I am able to delete the element from a list, but I have no idea how to write a function in Scheme to replace all occurences of an element in a list with another element. Any help will be appreciated.

+2  A: 

A simple version might be designed like this:

(define (replace old-element new-element list)
  ; if the list is null, just return null
  ; else if the car of the list is equal to old-element
  ;    run replace on the rest of the list, and cons new-element onto it
  ; else
  ;    run replace on the rest of the list, and cons the car onto it)

(I left the details up to you, since you gotta learn by doing.)

Remember, in Scheme the most natural way to do things will usually be to assemble a new list piece-by-piece from your old list, not to try to make little changes one at a time to your old list.

Note that you could also use map to do this much more concisely.

mquander
The syntax here is bad, it should be `(define (replace old new list) ...)`. As for the actual implementation -- don't do this, use `map`.
Eli Barzilay
I assumed that he is working from a guide or textbook that has gotten nowhere near `map` yet.
mquander
Any such book would have provided a similar kind of guiding, so it is either not needed because the book covers it, or because `map` is available.
Eli Barzilay
Fair enough, that's probably true.
mquander