Re: How to a matrix from a file



Yongwei Xing <jdxyw2004@xxxxxxxxx> writes:

Hi all

I have a txt file like below:

1 2 3 4 5 6
2 3 4 5 6 7
8 9 1 7 6 7
4 5 6 1 4 7

How can I read these data into a nested list? If the data is string or
char, is there any difference to do it?

Here's the lazy lisper solution:

(defun read-matrix (stream)
(loop
for line = (read-line stream nil nil)
while line
collect (read-from-string (concatenate 'string "(" line ")"))))

(with-input-from-string (example " 1 2 3 4 5 6
2 3 4 5 6 7
8 9 1 7 6 7
4 5 6 1 4 7
")
(read-matrix example))
--> ((1 2 3 4 5 6)
(2 3 4 5 6 7)
(8 9 1 7 6 7)
(4 5 6 1 4 7))

If your lines are not too long (eg. if they can be kept in a few L1
cache lines), time and space complexity will be dominated by
READ-FROM-STRING time, and CONCATENATE will be peanuts.

--
__Pascal Bourguignon__
http://www.informatimago.com
.