(方案)使用列表更改布尔数组中的值
(Scheme) Changing value in an array of booleans using a list
我需要创建一个大小为 800000 的布尔数组(0 或 1)。我还需要能够 check/change 索引处的值。 我不能使用向量或命令 set!
。
我在查看文档时发现 build-list
[1]。所以我做了一个这样的零数组:
(define arrBool (build-list 800000 (lambda (x) (* x 0))))
我知道我可以使用 list-ref
[ 2 ] 访问索引。但是,我在文档中找不到任何关于如何更改该索引处的值的信息。例如,如果我想将索引 27392 处的 0
更改为 1
,我将如何在不创建全新列表的情况下执行此操作?
任何帮助将不胜感激,谢谢!
你可以使用 boxes 虽然它很尴尬:
> (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
编辑
要在构建列表时将某些索引设置为 1,请执行
(define (make-list size indices-to-set)
(build-list size (lambda (i) (if (member i indices-to-set) 1 0))))
然后
> (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)
我需要创建一个大小为 800000 的布尔数组(0 或 1)。我还需要能够 check/change 索引处的值。 我不能使用向量或命令 set!
。
我在查看文档时发现 build-list
[1]。所以我做了一个这样的零数组:
(define arrBool (build-list 800000 (lambda (x) (* x 0))))
我知道我可以使用 list-ref
[ 2 ] 访问索引。但是,我在文档中找不到任何关于如何更改该索引处的值的信息。例如,如果我想将索引 27392 处的 0
更改为 1
,我将如何在不创建全新列表的情况下执行此操作?
任何帮助将不胜感激,谢谢!
你可以使用 boxes 虽然它很尴尬:
> (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
编辑
要在构建列表时将某些索引设置为 1,请执行
(define (make-list size indices-to-set)
(build-list size (lambda (i) (if (member i indices-to-set) 1 0))))
然后
> (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)