[plt-scheme] build-vector avoids sharing problem + tensor algebras

From: Richard C. Cobbe (cobbe at ccs.neu.edu)
Date: Wed Feb 5 08:38:06 EST 2003

Lo, on Tuesday, February 4, Bill Richter did write:

<SNIP>

> I'm writing some code to do some machine-intensive `tensor algebra'
> calculations that have been done in the past in C, but Scheme seems
> the right language, because there's so much recursion here.
> 
> I need a 2 parameter family of lists B(s,t), where 0 <= s, t < 50.
> 
> The list B(s,t) is computed from the earlier B(i, j) where either 
> j < t, or (i, j)  = (s-1, t).
> 
> Only solution that pops into my head is to make a 2-d vector by 
> 
> (define solution (build-vector 50 (lambda (n) (make-vector 50))))
> 
> and then, having computed the list B(s,t), stick it into solution by 
> 
> (vector-set! (vector-ref solution s) t ****)
> 
> and then I can use it later by 
> 
> (vector-ref (vector-ref solution s) t ****)

build-vector is indeed the right thing here: as you point out, the
straightforward uses of make-vector end up sharing the component
vectors, which is not what you want.

However, you may not necessarily need to use side effects to initialize
your arrays.  If you can write an expression that computes the value for
location (i,j) from i and j, why not simply use this in a nested
build-vector?  Something like the following:

(build-vector 50 
              (lambda (i) 
                (build-vector 50
                              (lambda (j)
                                (compute-element i j)))))

Here, compute-element may be your B(i,j); I didn't find the description
above very clear on this point.

There: no (explicit) side-effects.

Richard


Posted on the users mailing list.