I'm using vectors to build a table for implement a dynamic program, it involves updating each element of the vector sequentially. But why is there no vector-set
for immutable vectors? There is only vector-set!
for mutable vectors, but we can see that there is dict-set
and dict-set!
for immutable and mutable dictionaries, also there is hash-set
and hash-set!
for immutable and mutable hash tables.
The reason why vector-set
is missing, is to prevent people inadvertently using it without realizing the operation is O(n)
and not O(1)
. Since vector-set!
is O(1)
it is not unlikely for someone to make this mistake.
Furthermore it is simple to write a vector-set
when it is really needed:
#lang racket
(define (vector-set v i o)
(vector->immutable-vector
(for/vector ([j (in-range (vector-length v))])
(if (= i j)
o
(vector-ref v j)))))
(vector-set (vector-immutable 10 11 12 13) 2 'a)
Output:
'#(10 11 a 13)