Search code examples
arraysbooleanschemeracketbitvector

(Scheme) Changing value in an array of booleans using a list


I need to make an array of booleans (0 or 1) with size 800000. I also need to be able to check/change the value at an index whenever I can. I cannot use vectors or the command set!.

I was looking at the documentation and found build-list [ 1 ]. So I made an array of zeros like this:

(define arrBool (build-list 800000 (lambda (x) (* x 0))))

I know I can access an index with list-ref [ 2 ]. However, I cannot find anything in the documentation on how to change a value at that index. For example, if I want to change the 0 at index 27392 to a 1, how would I go about doing this without making a whole new list?

Any help would be appreciated, thanks!


Solution

  • You could use boxes although it's awkward:

    > (define arrBool (build-list 20 (lambda (x) (box 0))))
    > arrBool
    '(#&0 #&0 #&0 #&0 #&0 #&0 #&0 #&0 #&0 #&0 #&0 #&0 #&0 #&0 #&0 #&0 #&0 #&0 #&0 #&0)
    > (set-box! (list-ref arrBool 2) 1)
    > (set-box! (list-ref arrBool 9) 1)
    > arrBool
    '(#&0 #&0 #&1 #&0 #&0 #&0 #&0 #&0 #&0 #&1 #&0 #&0 #&0 #&0 #&0 #&0 #&0 #&0 #&0 #&0)
    > (unbox (list-ref arrBool 0))
    0
    > (unbox (list-ref arrBool 2))
    1
    

    EDIT

    To set some indices to 1 when building the list, do

    (define (make-list size indices-to-set)
      (build-list size (lambda (i) (if (member i indices-to-set) 1 0))))
    

    then

    > (make-list 20 '(2 9))
    '(0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0)