I'm new in Scheme. I want to get the number of occurence of a number in a vector.

I'm using this function on vectors whose 0th index is 0.

N is just the length of the vector - 1.

(I'm using this function as part of another function ... that's why I'm setting these requirements.)

This is what I got so far in DrRacket:

```
(define (frequency? test-num solutions N)
(do
((count 1 (+ count 1))
(result 0 (if (equal? (vector-ref solutions count) test-num) (add1 result) result)))
((<= count N) result)))
(define v (vector 0 3 2 4 5 2))
(frequency? 2 v 5) ; got 0 instead of 2
```

I checked that "result" gets changed to 1 on the 2nd index but somehow reverts back to 0 afterwards.

Is there any better way to write this code?

# Best How To :

Jens' answer is of course completely correct. You also ask whether there's another better way to write this code, and indeed I believe there is. I would probably write this code like this:

```
#lang racket
(define (frequency? test-num solutions)
(for/sum ([value (in-vector solutions)])
(if (equal? value test-num) 1 0)))
(define v (vector 0 3 2 4 5 2))
(frequency? 2 v) ; got 0 instead of 2
```

Note that there's no need to pass the length. There are of course many other ways to write it, including just `(length (filter (lambda (x) (equal? x test-num)) solutions)`

, but while that might be shorter, I think the one above is more readable.

In general, I think I speak for a reasonably large fraction of Racketeers when I say that `do`

is rarely the nicest way to express a program.

Cheers!