简体   繁体   中英

Racket recursion

I'm new to Racket and I'm trying to define a function that takes a list of divisors and a list of numbers to test, and applies direct recursion and a function 'drop-divisible' for each element in the list of divisors.

I defined a function drop-divisible which takes a number and a list of numbers, and returns a new list containing only those numbers not "non-trivially divisible" by the number. This function is not the problem, it works. So what I have trouble with is the function who is gonna call this function, and itself.

Here is what I've come up with. I can imagine that this is far from correct, but I have no idea what to do.

(define (sieve-with divisors testlist)
  (if (null? divisors)
      '()
      (begin
        (drop-divisible (first divisors) testlist)
              (sieve-with (rest divisors) testlist))))

You need to use tail recursion :

(define (sieve-with divisors list)
    (cond [(empty? divisors) list]
          [else (sieve-with (rest divisors)
                            (drop-divisible (first divisors) list))]))

Also, stay away from begin as much as possible. Stick to the functional paradigm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM