2017-06-09 81 views
0

我需要從文件中讀取,但我在代碼中遇到了一些問題。我已經讀我的文件是這樣的:每通過#\Space#\Tab分離線從文件中讀取Common Lisp

1.0 4.5 
4.555 6.43 
4.0 5 
..... 
6 3 

2號(文件中我能有行的一個大數目)。該函數讀必須返回一個列表如下:

((1.0 4.5)(4.555 6.43)(4.0 5)...(6 3)) 

我使用with-open-fileread-line和遞歸試過,但我有問題的處理流等,把這些元素在列表中以正確的方式

(with-open-file (in "foo.lisp" 
      :direction :input 
      :if-does-not-exist :error) 
(myread in)) 

(defun myread (filename) 
(let ((e (read-line filename nil ’eof)))) 

??? 

(cons (;;;numbers of current line;;;)(myread (filename))) 

我該怎麼做?感謝

回答

1

常用成語

(defun read-file-as-lines (filename) 
    "Read file into a list of lines." 
    (with-open-file (in filename) 
    (loop for line = (read-line in nil nil) 
     while line 
     collect line))) 

(defun line-as-list (line) 
    "Read all objects from the line as a list." 
    (read-from-string (concatenate 'string "(" line ")"))) 

(mapcar #'line-as-list (read-file-as-lines "mydata")) 

如果您擔心內存使用,你可以使用map-into代替mapcar甚至通過line-as-list作爲參數傳遞給read-file-as-lines

必讀

練習:在line-as-list中使用loop,而不是預先添加和附加括號。 這樣你可以控制你閱讀和處理多少個對象& c。

解決方案string-tokens