a multiple replace- function

Started by cormullion, April 04, 2007, 09:55:01 AM

Previous topic - Next topic

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:


(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:


(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:


(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

#1
Looking to it from this angle:



(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:



(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