Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching and replacing n element on list - scheme

Tags:

scheme

have got a problem with do this kind of code , can't figure how to search for a element (a) and replace i by ( b) , how to do it? Thx in advance

like image 466
user555446 Avatar asked Sep 10 '25 08:09

user555446


1 Answers

Start with a list. If it's empty, leave it. If the first element is a list, then you want to call your function recursively. If the first element is equal to what your searching for, cons the replacement onto a recursive call of your function on the rest of the list- you need to keep searching. If none of the earlier conditions are true, cons the first element on to a recursive call of your function for the rest of the list.

(define (find-replace a b list)
 (cond
  ((null? list) '())
  ((list? (car list)) (cons (find-replace a b (car list)) (find-replace a b (cdr list))))
  ((eq? (car list) a) (cons b (find-replace a b (cdr list))))
  (else
   (cons (car list) (find-replace a b (cdr list))))))
like image 189
Greg Avatar answered Sep 13 '25 01:09

Greg