Subject: Re: Style/effiency question. list->vector
From: rpw3@rigden.engr.sgi.com (Rob Warnock)
Date: 1996/11/21
Newsgroups: comp.lang.scheme
Message-ID: <570vnq$4nj@tokyo.engr.sgi.com>

William Annis <william@neurosim.wisc.edu> wrote:
+---------------
| I wanted to write list->vector  ...a naive implementation would
| traverse the list in question twice...
+---------------

Not sure there *is* any way to traverse the list just once if you want
to avoid allocating and throwing away lots of intermediate vectors...  ;-}

+---------------
| I'd be most interested to see a tail-recursive solution of the
| same problem. (Oh.  It's a stylist tic of mine to use letrec where
| I'd use labels or flet in CommonLisp.)
+---------------

I'm probably still way too fond of "do"...    ;-}  ;-}
but I'd probably do it something like this:

    (define (l2v lyst)
      (let ((the-vector (make-vector (length lyst))))
        (do ((i 0 (+ i 1))
             (ls lyst (cdr ls)))
            ((null? ls) the-vector)
          (vector-set! the-vector i (car ls)))))

Named-let also works reasonably well in this case, though it's textually
longer because you need either (cond) or (if Eb Et (begin ...)) to embrace
the two-expression body:

    (define (l2v lyst)
      (let ((the-vector (make-vector (length lyst))))
        (let loop ((i 0)
                   (ls lyst))
          (cond
            ((null? ls) the-vector)
            (else (vector-set! the-vector i (car ls))
                  (loop (+ i 1) (cdr ls)))))))


-Rob

-----
Rob Warnock, 7L-551                rpw3@sgi.com
Silicon Graphics, Inc.                http://reality.sgi.com/rpw3/
2011 N. Shoreline Blvd.                Phone: 415-933-1673  FAX: 415-933-0979
Mountain View, CA  94043        PP-ASEL-IA