Do at least n list elements satisfy a predicate?
; do-n? ; takes a list, returns #t if there are at least n elements ; that satisfy the predicate ; uses a helper procedure do-n-helper (define (do-n? lst) (do-n-helper lst 0)) (define (do-n-helper lst count) (cond [(null? lst) #f] [(pred? (car lst)) (if (>= (add1 count) n) #t ; stops the recursion (do-n-helper (cdr lst) (add1 count)))] [else (do-n-helper (cdr lst) count)]))
where n is a placeholder for some positive integer and,
again, pred? is a placeholder for some predicate.
Would it make sense to allow n to be zero?
How many elements satisfy a predicate?
; count-sat ; given a list, returns the number of elements in the list ; that satisfy a predicate (define (count-sat lst) (count-sat-helper lst 0)) (define (count-sat-helper lst count) (cond [(null? lst) count] [(pred? (car lst)) (count-sat-helper (cdr lst) (add1 count))] [else (count-sat-helper (cdr lst) count)]))
Exercise: what is a suitable instantiation of pred? to determine how many elements in a list are themselves lists?