a multiple replace- function

Q&A's, tips, howto's
Locked
cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

a multiple replace- function

Post by cormullion »

I've again found myself thinking that it would be nice to be able to make a series of replacements with a single call:

Code: Select all

(replace "Sherlock" text "Ellery" 0)
(replace "Holmes" text "Queen" 0)
- well, there could be loads of them. Putting the pairs into a list is OK:

Code: Select all

(map (fn (e) (replace (first e) text (last e) 0)) '(("Sherlock" "Ellery") ("Holmes" "Queen")))
but it would be neater to have a 'replace-all' or 'replace-each' function, that takes lists:

Code: Select all

(replace-each '("Sherlock" "Holmes") text '("Ellery" "Queen") 0) 
Could be cool - but perhaps it wouldn't work?



I don't know why I posted this in the Windows area. Sorry. Slip of the mouse...

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

Looking to it from this angle:

Code: Select all

(set 'text "Sherlock Holmes")
(set 'repls '(("Sherlock" "Ellery") ("Holmes" "Queen")))

(dolist (r repls)
    (replace (first r) text (last r)))
it is easy to write this hygienic macro:

Code: Select all

(define-macro (replace-all)
    (dolist (r (eval (args 0)))
        (replace (first r) (eval (args 1)) (last r))))

> (replace-all repls text)
"Ellery Queen"
> text
"Ellery Queen"
> 
I find it practical to keep the replacemant pairs together in case there is a larger list of replacements.

Lutz

Locked