In: Computer Science
You must write each of the following scheme functions. You must use only basic scheme functions do not use third-party libraries to support any of your work. Do not use any function with side effects.
Write a function named (list-replace ALIST SYM VAL) that accepts a list of elements and returns that list where all SYM's (a single symbol) have been replaced by the VAL (some scheme value). The replacement must occur even within nested lists. For example:
(list-replace '(a b c) 'a 3) ---> (3 b c) (list-replace '(a (a b c) c) 'a 3) ---> (3 (3 b c) c) (list-replace '() 'a 3) ---> () (list-replace '(a (a (a))) 'a '(3)) --> ((3) ((3) ((3))))
Let's see this input to the function first,
We have a string that has a set of symbols (characters)
Then we have a character (X) we need to replace all of that with a digit , our third input (Y).
Now the straight solution is using a replace function, but given that we can't use a third party solution we'll basically build that replace function.
Def funtion_name(str1, character, digit):
Newstring = ''#this string will hold returns for i in str1: if i == star(character): i = digit Newstring += i Return (Newstring)
So to explain the approach, we can basically just go through the string character by character, as shown in the loop.
For each character we check if that is the SYM we have to replace, and if it is so we make the iteration variable as I= VAL which we need to put in place of the SYM and then all I are added to the new string.
This way after all characters are done in the string, we initially got we are done with the the string we need in the newstring variable and we return it.