Kaylee YunKyung Kim
Kaylee YunKyung Kim

Reputation: 77

racket: update the list

i need to update my list but it doesn't work well.

so lets say i have two list.

(define list1 '(1 2 3 4 5 6 7 8 9 10))
(define list2 '())

1.    (define (divisionlist symbol1 symbol2 list newlist)
2.      (cond [(empty? list) null]
3.        [(equal? symbol2 (car list)) 
4.                         (divisionlist symbol1 symbol2 (cdr list) newlist)]
5.        [(equal? symbol2 (remainder (car list) symbol1)) 
6.                         (append newlist (car list)) 
7.                         (divisionlist symbol1 symbol2 (cdr list) newlist)]
8.        [else 
9.                (divisionlist symbol1 symbol2 (cdr list) newlist)]))

(divisionlist 3 1 list1 list2)

what i am trying to do is to find integer that has remainder as 1 if i divide with 3. so with my list1, the result is going to be '(4 7 10). i want to insert my result one by one into list2 which is "newlist" in the function division list. but on 6th line of the code, the "append" doesn't not insert my result into the newest. anyone have idea??? thank you so much!

Upvotes: 3

Views: 865

Answers (1)

Óscar López
Óscar López

Reputation: 236170

In Scheme the list procedures do not update lists in-place, they return a new list as a result, and you must do something with the returned value - say, assign it to a variable or pass it along as parameter. What we can do is build a new list as a result of calling the procedure, and if needed assign it to a variable afterwards. For example:

(define (divisionlist symbol1 symbol2 lst) ; don't call a parameter `list`
  (cond [(empty? lst) null]
        [(equal? symbol2 (car lst))
         (divisionlist symbol1 symbol2 (cdr lst))]
        [(equal? symbol2 (remainder (car lst) symbol1))
         ; notice how we use `cons` to build a new output list
         (cons (car lst) (divisionlist symbol1 symbol2 (cdr lst)))]
        [else 
         (divisionlist symbol1 symbol2 (cdr lst))]))

(define list1 '(1 2 3 4 5 6 7 8 9 10))
(define list2 (divisionlist 3 1 list1))

Now list2 will contain the expected value:

list2
=> '(4 7 10)

Upvotes: 3

Related Questions