Count occurrence of element in a list in Scheme?

In Racket, you could do

(count even? '(1 2 3 4))

But more seriously, doing this with lists in Scheme is much easier that what you mention. A list is either empty, or a pair holding the first item and the rest. Follow that definition in code and you’ll get it to “write itself out”.

Here’s a hint for a start, based on HtDP (which is a good book to go through to learn about these things). Start with just the function “header” — it should receive a predicate and a list:

(define (count what list)
  ...)

Add the types for the inputs — what is some value, and list is a list of stuff:

;; count : Any List -> Int
(define (count what list)
  ...)

Now, given the type of list, and the definition of list as either an empty list or a pair of two things, we need to check which kind of list it is:

;; count : Any List -> Int
(define (count what list)
  (cond [(null? list) ...]
        [else ...]))

The first case should be obvious: how many what items are in the empty list?

For the second case, you know that it’s a non-empty list, therefore you have two pieces of information: its head (which you get using first or car) and its tail (which you get with rest or cdr):

;; count : Any List -> Int
(define (count what list)
  (cond [(null? list) ...]
        [else ... (first list) ...
              ... (rest list) ...]))

All you need now is to figure out how to combine these two pieces of information to get the code. One last bit of information that makes it very straightforward is: since the tail of a (non-empty) list is itself a list, then you can use count to count stuff in it. Therefore, you can further conclude that you should use (count what (rest list)) in there.

Leave a Comment