0

i did the function search that takes a los, a number, and returns the numth symbol of the list. simple

(define (search los num)
  (cond
    [(empty? los) empty]
    [(zero? num) (first los)]
    [else (lookup (rest los) (- num 1))]))

(check-expect (lookup (list 'a 'b 'c 'd) 0) 'a)

but i am having trouble figuring out how to design a function that takes a los (list of symbols) , a symbol (s) , and a number (numth) , and returns los with numth symbol replaced with s.

like something like this-

(change (list 'a 'b 'c 'd) 'hello 2) ;==> (list 'a 'b 'hello 'd)
(change (list 'a 'b 'c 'd) 'hi 0) ;==> (list 'hi 'b 'c 'd)
1
  • did you intend to name your function lookup and not search, perhaps? Commented Mar 11, 2013 at 14:21

2 Answers 2

2

Here is a solution:

(define (change los s num)
  (cond ((null? los) '())
        ((< num 0) los)
        ((= num 0) (cons s (cdr los)))
        (else (cons (car los) (change (cdr los) s (- num 1))))))

Basically, the idea is to recreate the list recursively, but with a twist (replacing the nth symbol with s).

So, to recursively "recreate" the list, I could:

(define (lst los)
  (if (null? los)
    '()
    (cons (car los) (lst (cdr los)))))

Our parameters for change give us the symbol to replace with, and the position to replace. So we count down, recreating the list until that point. Then, when we have counted down to 0, we can replace the current symbol in the list with the new symbol by just cons'ing it in instead of the current symbol. I added the < 0 check just because.

Sign up to request clarification or add additional context in comments.

Comments

2

First, think about how to copy a list. This won't involve the num parameter.

Then, use the same num-decrementing approach you have in search to replace (instead of copy) the list element if num is 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.