Sujet : Re: removeText
De : Nobody447095 (at) *nospam* here-nor-there.org (B. Pym)
Groupes : comp.lang.lisp comp.lang.schemeDate : 01. Jul 2025, 21:15:07
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <1041fk9$31mat$1@dont-email.me>
References : 1
User-Agent : XanaNews/1.18.1.6
B. Pym wrote:
Peter Seibel wrote:
Kenny Tilton <ktilton@nyc.rr.com> writes:
Cool. Now here is a version using loop:
(defun remove-text (text-to-remove text)
(loop with remove-length = (length text-to-remove)
for i = (search text-to-remove text)
then (search text-to-remove text :start2 i)
while i
do (setq text (concatenate 'string
(subseq text 0 i)
(subseq text (+ i remove-length))))
finally (return text)))
Just to point out a useful LOOP idiom, here's another way:
(defun remove-text (text-to-remove text)
(with-output-to-string (s)
(loop
with remove-length = (length text-to-remove)
for prev-end = 0 then (+ start remove-length)
for start = (search text-to-remove text :start2 prev-end)
do (write-string text s :start prev-end :end start)
while start)))
If we use a Lispy language instead of CL, then we can
make the solution shorter by simply using recursion
instead of a macro whose source measures more than
60 kilobytes.
Gauche Scheme
(use srfi-13) ;; string-contains
(define (remove-text victim text)
(let1 victim-length (string-length victim)
(with-output-to-string
(lambda()
(let go ((start 0))
(let1 p (string-contains text victim start)
(display (string-copy text start p))
(when p (go (+ p victim-length)))))))))
(remove-text " not" "CL is not bad and not a nightmare.")
===>
"CL is bad and a nightmare."
Using "do":
(define (remove-text victim text)
(let ((victim-length (string-length victim)) (p 0))
(with-output-to-string
(lambda()
(do ((start 0 (+ p victim-length)))
((begin
(set! p (string-contains text victim start))
(display (string-copy text start p))
(not p))))))))