newLISP Fan Club

Forum => newLISP in the real world => Topic started by: cormullion on April 04, 2007, 09:55:01 AM

Title: a multiple replace- function
Post by: cormullion on April 04, 2007, 09:55:01 AM
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...
Title:
Post by: Lutz on April 05, 2007, 02:16:52 AM
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