Racket: refresh the list

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

so let's say I have two lists.

(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 find an integer with remainder as 1 if i divide by 3. so with my list1 the result will be "(4 7 10). I want to insert my result one by one into list2 which is" new list "in the list of functions. but on the sixth line of code" append "doesn't insert my result into the newest one. who has an idea ??? Thank you so much!

+3


source to share


1 answer


In the schema, list procedures do not update lists in place, so they return a new list, and you must do something with the return value β€” for example, assign it to a variable or pass it as a parameter. We can create a new list as a result of a procedure call and assign it to a variable if needed. 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))

      



list2

Will now contain the expected value:

list2
=> '(4 7 10)

      

+3


source







All Articles