Reputation: 13
I am trying to write a function that takes a list of divisors, a list of numbers to test and applies drop-divisible for each element of the list of divisors. I am supposed to use filter, map or foldl and no recursion
I wrote the drop-divisible function:
(define (drop-divisible l n)
(cond
[(empty? l) empty]
[(empty? (rest l)) l]
(let ([i (first l)])
(if (zero? (modulo i n))
(drop-divisible (rest l) n)
(cons i (drop-divisible(rest l)n))))]))
That seems to work, but I'm confused on how I can call drop-divisible for each element in the list when it only wants one list and an integer as a parameter?
Hopefully, that makes sense, thanks
Upvotes: 1
Views: 688
Reputation: 5020
When you want "all the elements of this list except the ones that meet such-and-such criterion", the filter
function provides an easy way to do that:
(define (drop-divisible l n)
(filter (λ (i) (not (zero? (modulo i n))))
l))
> (drop-divisible '(4 6 9 8 12 14) 3)
'(4 8 14)
filter
constructs a new list, containing only the items of the original list that meet your criterion. The first argument to filter
is a function that takes a single element of the list and returns #f
if the element should be skipped when creating the new list, and returns any other value to include the element in the new list. The second argument to filter
is the list to filter.
In other words, filter
does exactly what your code does, but it's generalized to apply any filtering criterion.
Upvotes: 1