从文件 Common Lisp 中读取

Mel*_*low 2 lisp file common-lisp

我需要从文件中读取,但我的代码有一些问题。我必须像这样阅读我的文件:

1.0 4.5
4.555 6.43
4.0 5
.....
6 3
Run Code Online (Sandbox Code Playgroud)

每行 2 个数字由#\Space或分隔#\Tab(在文件中我可以有很多行)。函数 read 必须返回一个像这样的列表:

((1.0 4.5)(4.555 6.43)(4.0 5)...(6 3))
Run Code Online (Sandbox Code Playgroud)

我试过使用with-open-file,read-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)))
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?谢谢

sds*_*sds 5

通常的成语

(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"))
Run Code Online (Sandbox Code Playgroud)

如果您关心内存使用,您可以使用map-into代替mapcar甚至line-as-list作为参数传递给read-file-as-lines.

必读

练习:使用loopinline-as-list而不是前置和后置括号。通过这种方式,您可以控制读取和处理评论的对象数量等。

解决办法string-tokens