Sania
Sania

Reputation: 93

Replacing a String in a List in Racket

I am trying to replace a string in the list with another given string, using abstract list functions and lambda only. The function consumes lst, a list of strings, str, the string you are replacing, and rep, the string you are replacing str with. Here is an example: (replace (list "hi" "how" "are" "you") "hi" "bye") -> (list "bye" "how" "are" "you")

Written below is the code that I wrote in recursion and it works.

(define (replace lst str rep)
  (cond [(empty? lst) empty]
        [(equal? match (first lst))
           (cons rep (replace-all (rest lst) match rep))]
        [else (cons (first lst) (replace-all (rest lst) match rep))]))

Below that code is what I have tried but I'm not sure how to fix it to make it produce what I want.

(define (replace lst str rep)
   (map (lambda (x) (string=? x str)) lst))

Any and all help is appreciated, thanks!

Upvotes: 0

Views: 1682

Answers (1)

Óscar López
Óscar López

Reputation: 236004

Almost there! you just have to ask, for each string: is this the one I want to replace? then replace it - otherwise leave it untouched:

(define (replace lst str rep)
  (map (lambda (x) (if (string=? x str) rep x)) 
       lst))

Upvotes: 2

Related Questions