Subject: Re: Collecting nested lists in Loop
From: rpw3@rpw3.org (Rob Warnock)
Date: Tue, 22 Nov 2005 01:58:45 -0600
Newsgroups: comp.lang.lisp
Message-ID: <L4CdnQFJFukoUh_eRVn-tg@speakeasy.net>
Alan Crowe  <alan@cawtech.freeserve.co.uk> wrote:
+---------------
| You may wish to enjoy the fact that the initial contents to make-array
| is a nested structure of sequences. Thus one may mix lists and vectors
| and indeed a relevant list of vectors is easily come by
| CL-USER> (defun letter-matrix (stream)
|            (let ((lines (loop for line = (read-line stream nil nil)
|                               while line
|                               collect line)))
|              (make-array (list (length lines)
|                                (length (car lines)))
|                          :initial-contents lines)))
| LETTER-MATRIX
| CL-USER> (with-input-from-string (stream "abcd
| efgh
| ijkl")
|            (letter-matrix stream))
| #2A((#\a #\b #\c #\d) (#\e #\f #\g #\h) (#\i #\j #\k #\l))
+---------------

And by specializing the array with some subtype of CHARACTER,
one can also explore some of the consequences of arrays being
stored in row-major order:

    > (defun letter-matrix (stream)
	(let ((lines (loop for line = (read-line stream nil nil)
			   while line
			   collect line)))
	  (make-array (list (length lines)
			    (length (car lines)))
		      :initial-contents lines
		      :element-type 'base-char)))

    LETTER-MATRIX
    > (with-input-from-string (stream "Here we
    have an
    example
    that is
    so fun.
    ") (letter-matrix stream))

    #2A((#\H #\e #\r #\e #\  #\w #\e)
	(#\h #\a #\v #\e #\  #\a #\n)
	(#\e #\x #\a #\m #\p #\l #\e)
	(#\t #\h #\a #\t #\  #\i #\s)
	(#\s #\o #\  #\f #\u #\n #\.))
    > (make-array (reduce #'* (array-dimensions *))
		  :element-type 'base-char
		  :displaced-to *)

    "Here wehave anexamplethat isso fun."
    > (type-of *)

    (BASE-STRING 35)
    > (setf (aref *** 4 6) #\!)

    #\!
    cmu> ***

    "Here wehave anexamplethat isso fun!"
    > 

Thus showing that the two-dimensional array really is, in this case,
"the same" string as the displaced array.


-Rob

-----
Rob Warnock			<rpw3@rpw3.org>
627 26th Avenue			<URL:http://rpw3.org/>
San Mateo, CA 94403		(650)572-2607