从Common Lisp文件中读取

时间:2017-06-09 20:12:18

标签: file lisp common-lisp

我需要从文件中读取,但我遇到了一些代码问题。我要读这样的文件:

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

每行2个数字,由#\Space#\Tab分隔(在文件中我可以有大量的行)。函数read必须返回如下列表:

((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 个答案:

答案 0 :(得分:2)

通常的习语

(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

必读>

练习:在loop中使用line-as-list,而不是预先添加和附加括号。 这样,您就可以控制阅读的对象数量并处理注释& c。

解决方案string-tokens