204k views
0 votes
Write a Scheme function that takes two atoms and a list as parameters and returns a list identical to the parameter list except all occurrences of the first given atom in the list are replaced with the second given atom, no matter how deeply the first atom is nested.

User Alexmorhun
by
5.7k points

1 Answer

4 votes

Answer:

(define (delete-atom list atom )

(cond ((null? list) '()) ;;if list is empty returns empty

((equal? (car list) atom) (delete-atom (cdr list) atom)) ;;checking fiest element of element of list with item

(else (cons (car list) (delete-atom (cdr list) atom))))) ;;recursively check for rest of the elements

Step-by-step explanation:

atom is first compared with first element of list, if both are equal it recursively calls that function with deleting first element. if both are not equal it cons the first element and recursively calls rest of the elements.

Obeserve that if list is nested list for ex '((1 2) 2 3) and if we want to delete 2 it returns ((1 2) 3) becuase it deletes top level of 2 only. when (car list) i., (2 3) compared with 2, both are not equal and it cons the entire sublist ((2 3) and recursively calls delete-atom function. so it doesn't deletes the element inside and deletes top level only.

Consider a simple list '( 1 2 3). Here deleting 1 is just a simple deletion and returns (2 3)

consider deleting 1 from top level of a nested list '(1 2 3 (1 3) 1 3 4) returns (2 3 (1 3) 3

User Gubbel
by
6.6k points