将文件输入流中的列表存储在LISP中的变量中

时间:2017-04-17 11:32:21

标签: lisp common-lisp

我可以在.txt文件中说出以下列表

(5 3 1)

我正在尝试使用以下源代码将上面的列表存储在LISP中的变量中。在第一种格式之前,一切似乎都是对但后来我意识到*originalStateVar*没有被视为具有3个原子的列表,而是作为具有1个原子的列表。源代码如下:

(defvar *originalStateVar*)
(defun fileInput ()
  (let ((i 1)(in (open *originalStateLocation* :if-does-not-exist nil)))
        (when in
            (loop
                for line = (read-line in nil)
                while line do 
                    (format t "~a~%" line)                ;debug line
                    (format t "i is <~a>~%" i)            ;debug line
                    (setf *originalStateVar* (list line)) ;storing list in variable
                    (setf i (+ i 1)))                     ;debug line
            (close in))
        (format t "originalStateVar is <~a>" (car *originalStateVar*))
        (format t "second element originalStateVar is <~a>~%" (cadr *originalStateVar*))
        (format t "third element originalStateVar is <~a>~%" (caddr *originalStateVar*))))

上述代码的输出是:

(5 3 1)
i is <1>
first element originalStateVar is <(5 3 1)>
second element originalStateVar is <NIL>
third element originalStateVar is <NIL>

我所知道的是,它将(5 3 1)存储为列表中的单个原子,因此它变为((5 3 1)),这就是cadr返回{{}的原因1}}。

如何让NIL以这种方式得到对待的任何帮助,将不胜感激!

1 个答案:

答案 0 :(得分:5)

  • 使用WITH-OPEN-FILE代替OPEN
  • 使用READ代替READ-LINE

示例:

CL-USER 11 > (let ((*read-eval* nil))
               (with-open-file (in "/tmp/test.data")
                 (read in)))
(1 2 3)

CL-USER 12 > (let ((*read-eval* nil))
               (with-open-file (in "/tmp/test.data")
                 (describe (read in))))

(1 2 3) is a LIST
0      1
1      2
2      3