Reputation: 21
Using 'filter' I need to write a code to reate a procedure called (count-zeros lst) that counts how many 0s are in a number. Sample output: (count-zeros '(1 1 0 1 0 0)) should give 3
(define filter (lambda (pred a-list)
(if (null? a-list)
'()
(if (pred (car a-list))
(cons (car a-list) (filter pred (cdr a-list)))
(filter pred (cdr a-list))))))
(define (count-zeros lst)
(filter zero? (length lst)))
I know the logic is right but I have troubles with the implementation and making the code work. Please help me to improve the code.
Upvotes: 0
Views: 189
Reputation: 236034
Read the problem statement carefully, and compare it against what you wrote: it says count the number of zeroes, but you're taking the length of the list (which returns a number!) and then trying to filter the zeroes out of that number, which doesn't make sense. It's the other way around:
(define (count-zeros lst)
(length (filter zero? lst)))
First we filter just the zeroes, which returns a list, and then we get the length of that list.
Upvotes: 1