(defun foo(mylist) (with-open-file(str“out.txt”) :方向:输出 :if-exists:追加 :if-does-not-exists:create) (如果……
此错误记录在 手册 。 你在打电话 foo 递归地,每次调用再次打开文件。 这可能会产生非常糟糕的后果。
foo
您可以通过移动外部的递归调用来修复它 with-open-file :
with-open-file
(defun write-list-to-file-reopen (mylist destination) (when mylist (with-open-file (str destination :direction :output :if-exists :append :if-does-not-exist :create) (prin1 (pop mylist) str) (terpri str)) (write-list-to-file-reopen mylist)))
但这是非常低效的,因为 open 是一个相对昂贵的操作。
open
一个更好的解决方案是迭代
(defun write-list-to-file-iterate (mylist destination) (with-open-file (str destination :direction :output :if-exists :append :if-does-not-exist :create) (dolist (el mylist) (format str "~S~%" el))))
或者,如果您需要使用递归,
(defun write-list-to-file-recursion (mylist destination) (with-open-file (str destination :direction :output :if-exists :append :if-does-not-exist :create) (labels ((write-list (list) (when list (prin1 (pop list) str) (terpri str) (write-list list)))) (write-list mylist))))
功能 format 是相对的 重量很重,可用于交互式漂亮打印 喜欢使用更简单的功能 write 。
format
write
你的问题是因为你的 (format str x) 应该 (format str "~S~%" x) : 你忘记了 格式字符串 。
(format str x)
(format str "~S~%" x)