gpt4 book ai didi

LISP - 将列表写入文件

转载 作者:太空宇宙 更新时间:2023-11-03 18:53:36 24 4
gpt4 key购买 nike

我需要将一个数字列表写入一个文件,并在该行的末尾放置一个return

我试过这段代码,但只对列表的第一个元素有效。

(defun write-segment (filename segment)
(cond ((null segment)
(with-open-file (out filename
:direction :output
:if-exists :append
:if-does-not-exist :create)
(format out "~%")))
(T (with-open-file (out filename
:direction :output
:if-exists :append
:if-does-not-exist :create)
(format out "~D " (first segment))
(write-segment filename (cdr segment))))))

有人可以帮我解决这个问题吗?

最佳答案

像这样将 % 附加到流中怎么样:

(with-open-file (str "filename.txt"
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(format str "~A~%" '(1 2 3 4 5)))

在你的情况下,我会做一些事情,比如遍历列表并写入流,像这样的事情,小心额外的返回,如果你不想做,你也可以在打开文件之前添加一个控件如果列表为空,则执行任何操作。

(defun write-non-empty-list-to-a-file (file-name lst)
"writes a non empty list to a file if the list is empty creates the file with a return"
(with-open-file (str file-name
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(dolist (e lst)
(format str "~A~%" e))
(format str "~%")));this if you want an extra return

关于LISP - 将列表写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38507228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com