[plt-scheme] Some things about the Vector type that are not mentioned in normal documention
On Nov 27, 2004, at 4:19 PM, Devlin Bentley wrote:
> As a new user to Scheme, I recently tried to implement a 2D array as a
> vector of vectors in PltScheme. Obviously things did not go well for
> me (I used Make-Vector and I filled the vector with another set of
> vectors.)
>
> Now nowheres in the included documentation, t-y-scheme or the PLT
> MzScheme language manual, is anything mentioned about this being an,
> ...., issue.
As Robby points out and explains, it isn't an issue and therefore
doesn't deserver mentioning. You would get the same result in any
programming language, be that C or Java or Prolog or Haskell (lazy
means you save a reference to this inner vector). Every function call
evaluates all arguments. Some languages offer syntax that looks like a
function call but is really not and duplicates things for you. So you
should be grateful for the lesson. You have finally understood the
essence of call-by-value in a world with compound objects.
As for your problem, you may wish to consider two different solutions:
;; Nat Nat (Nat Nat -> X) -> Matrix[X]
(define (build-matrix n m f)
(build-vector n (lambda (i) (build-vector m (lambda (j) (f i j))))))
;; Matrix[X] Nat Nat -> X
(define (matrix-ref M i j)
(vector-ref (vector-ref M i) j)))
;; suitable dimension check omitted
or
;; Nat Nat (Nat Nat -> X) -> Matrix[X]
(define (build-matrix n m f)
(list->vector (apply append (build-list n (lambda (i) (build-list m
(lambda (j) (f i j))))))))
with a suitable deferencing schema. It's much faster than the first one.
-- Matthias