The fold answers will work. However, if this is homework, you may be trying to do this using only simple built-in functions. There are two possible answers.
Here's the naive way:
(define (howMany list)
(if (null? list)
0
(+ 1 (howMany (cdr list)))))
(Your implementation of Scheme may have a function empty?
instead of null?
.)
However, this algorithm will take an amount of space linearly proportional to the number of elements in the list, because it will store (+ 1 ...)
for each element of the list before doing any of the additions. Intuitively, you shouldn't need this. Here's a better algorithm that avoids that issue:
(define (howMany list)
(define (iter numSoFar restOfList)
(if (null? list)
numSoFar
(iter (+ numSoFar 1) (cdr list))))
(iter 0 list))
(Bonus points: use Scheme's (let iter ...)
syntax to write this more succinctly. I used this style because it's more clear if you only know a few Scheme primitives.)