In: Computer Science
scheme:
Write a recursive Scheme function (subst x y L), which returns a list identical to L except that every occurrence of x has been replaced with y. The following example illustrates the use of this function: > (subst 'c 'k '(c o c o n u t)) (k o k o n u t)
Write a recursive Scheme function (all-different? L), which determines whether all elements of list L are distinct (that is, not equal?). The following example illustrates the use of this function: > (all-different? '(3 7 2 7)) #f
car gets the first pointer
cdr gets the second pointer
cpr and ctr are not required for this task
One method of doing it:
(define (subst k c list) #; define the substitute procedure
(cond #; conditional computation
#; Syntax: cond < phrase 1 > < phrase 2 > etc ……..
#; where phrase = (<test> <expression> …….. )
#; that is, cond (<test> <expression> <test> <expression> …….)
((null? list) ‘()) #; make sure that the list is not null
#; cons will construct objects of memory to hold a couple of values
#; it may also hold couple of pointers to those values
#; ( cons c o c o n u t ) will construct (c . o . c . o . n . u . t)
#; can also be written as (c.(o. (c. (o. (n. (u. (t. nil)))))))
((list? (car list)) (cons (subst k c (car list)) (subst k c (cdr list))))
#; car list will get the first element in our case car (cococnut) returns c
#; cdr list returns the second or last pointer
((eq? (car list) k) (cons c (subst k c (cdr list))))
#; check for equality, if equal construct by replacing c with k
#; hence coconut will become kokonut, cat become kat, circuit becomes kirkuit etc
(else
#; in the else case construct by getting the first element of the list c and calling the subst method again
(cons (car list) (subst k c (cdr list))))))
#’ end of the scheme method
#; this is a comment line
#; (caar ‘((c o) (n u t))) is equivalent to
#; (car (car ‘((c o) (n u t))))
#; the result is c
#; because ( car ‘((c o) (n u t))) will return (c n )
#; then the outer car written as
#; ( car ( c n) ) will return c
#;
#| this is a multi line comments block
spanning over few lines of commenting
Scheme is similar to LISP the language of Artificial Intelligence, Humanoids, Matrix Agents and Robotics
up to this line is a block of comments in scheme |#