So I'd like to generate a bit vector in scheme. Then take a somethings value after a hash function h(v) = X . Then set that position in the bit-vector from 0 to 1. Any ideas on how to create a bit vector and then manipulate specific positions in the vector? Thanks

# Best How To :

As you mention, we can use a `vector`

data structure to represent a bit vector in Scheme, refer to your interpreter's documentation. As a first step, create a new `vector`

with the maximum number of elements that you expect, and initialize it with zeroes. For example, to create a vector of size `10`

do this:

```
(define bit-vector (make-vector 10 0))
bit-vector
=> '#(0 0 0 0 0 0 0 0 0 0)
```

To set an index in a given value use `vector-set!`

. Let's say that we want to set the index `3`

with a value of `1`

, and notice that the `!`

at the end (pronounced *bang!*) indicates that this procedure mutates the vector in-place:

```
(vector-set! bit-vector 3 1)
bit-vector
=> '#(0 0 0 1 0 0 0 0 0 0)
```

And finally, to retrieve the value at a given index we use `vector-ref`

:

```
(vector-ref bit-vector 3)
=> 1
```

For the second part: how can we obtain a list of the indexes where the values are true? there are several ways, all involving traversing the vector, testing the value at each position and accumulating the result in a list. For example, using explicit recursion:

```
(define (true-indexes bit-vector)
(let loop ([idx (sub1 (vector-length bit-vector))] [acc '()])
(cond ((negative? idx) acc)
((= (vector-ref bit-vector idx) 1)
(loop (sub1 idx) (cons idx acc)))
(else
(loop (sub1 idx) acc)))))
```

If you're lucky and use a sophisticated Scheme interpreter we can write an idiomatic solution in terms of iterations and comprehensions. For example, in Racket:

```
(define (true-indexes bit-vector)
(for/list ([(val idx) (in-indexed bit-vector)]
#:when (= val 1))
idx))
```

Either way, it works as expected:

```
(true-indexes (vector 0 0 1 0 1))
=> '(2 4)
```