2016-07-21 58 views
0

我需要寫一個數字列表到一個文件並在行尾加上returnLISP - 寫一個列表到文件

我已經嘗試使用此代碼,但僅適用於列表的第一個元素。

​​

有人可以幫我解決這個問題嗎?

+2

你的代碼是不可讀的 - 請修復縮進。 – sds

+3

您正在打開每個列表元素的文件。這是非常低效的。 – sds

回答

0

從描述和代碼,我不是100%確定如果以下適合你以後,但我會嘗試反正。在這個片段中的代碼走數值的清單,並將其寫入到輸出文件:

(defun write-numeric-list(filename l) 
    (with-open-file (out filename :direction :output :if-exists :append :if-does-not-exist :create) 
    (dolist (segment l) 
     (format out "~D " segment)) 
    (format out "~%"))) 

樣品電話:

(write-numeric-list "output.txt" (list 1 2 -42)) 

這段代碼打開輸出文件只有一次的整個列表,而不是對於列表中的每個元素都是一次,就像在原始版本中一樣。您可能需要根據您在特定情況下的先決條件調整:if-exists:if-does-not-exist選項。

實際上,format可以使用稍微高級的格式控制字符串,僅僅通過它自己的列表。那些控制字符串並不是每個人的茶,但作爲參考,這裏是使用它們的代碼的一個版本:

(defun write-numeric-list(filename l) 
    (with-open-file (out filename :direction :output :if-exists :append :if-does-not-exist :create) 
    (format out "~{~D ~}~%" l))) 
+0

對於附加的黑客值,格式控制可以是'「〜{〜D〜^〜}〜%」' – tfb

-1

看來你想要做遞歸。 我會做這樣然後

(defun write-segment (filename segment) 
    (labels 
     ((do-write (out segment) 
     (cond ((null segment) (format out "~%")) 
       (t (format out "~D " (car segment)) 
        (do-write out (cdr segment)))))) 
    (with-open-file (out filename 
        :direction :output 
        :if-exists :append 
        :if-does-not-exist :create) 
    (do-write out segment)))) 
+0

堆棧溢出。附加到現有文件的 –

+0

。 –

2

什麼附加%到流這樣的:

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

在你的情況,我會做一些事情,比如去througth列表,並寫入流,有些事情是這樣的,小心額外的返回,如果你不想做任何事情,如果列表是空的,你也可以在打開文件之前添加一個控件。

(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 
+0

或者也許'(format str「〜{〜A〜%〜}〜%」lst)' – coredump

相關問題