scheme - Replace first occurrence of symbol in (possibly nested) list -
i replace first occurrence of symbol (say '-
) symbol (say '+
) inside list may contain lists. say,
'(((-)))
turn '(((+)))
'((-) - b)
'((+) - b)
here's another, different option: using mutable state find out when first replace has happened:
(define (replace-first) (let ((found #f)) (define (replacer exp old new) (cond ((null? exp) '()) ((not (pair? exp)) (cond ((and (eq? exp old) (not found)) (set! found #t) new) (else exp))) (else (cons (replacer (car exp) old new) (replacer (cdr exp) old new))))) replacer)) ((replace-first) '(((-))) '- '+) => '(((+))) ((replace-first) '((-) - b) '- '+) => '((+) - b) ((replace-first) '(+ 1 2) '+ '-) => '(- 1 2) ((replace-first) '((+) 1 2) '+ '-) => '((-) 1 2) ((replace-first) '(1 2 ((+)) 3 4) '+ '-) => '(1 2 ((-)) 3 4) ((replace-first) '() '+ '-) => '() ((replace-first) '(1 2 ((((((+ 3 (+ 4 5)))))))) '+ '-) => '(1 2 ((((((- 3 (+ 4 5))))))))
Comments
Post a Comment