How to add list in file to Lisp -
i want add list in text file lisp , bound variable. example mylist.txt contains: ((1 2 3 4) (5 6 7 8) (9 10 11 12) (13 14 15 16) ) , want read file , and set list variable mylist.
(defun readfile (filename) (let ((in (open filename :if-does-not-exist nil))) (when in (loop line = (read in nil) while line (print line)) (close in) ) ) ) (setf mylist (readfile "list.txt")) output should (mylist should bounded to): ((1 2 3 4) (5 6 7 8) (9 10 11 12) (13 14 15 16) )
i have seen of answer on stackflow regarding this, non them worked example tried reading line line , used collect dont seem give me right answer since collect's entire line , treat list item.
as stands far reading file , printing standard output ((print line) statement in readfile). instead, want collect input.
(defun read-file (file-name) (let ((*read-eval* nil)) (with-open-file (in file-name) (loop x = #1=(read-line in nil :eof) #1# until (eq x :eof) collect (read-from-string x))))) line-by-line: 1. please, use cl conventions names. 2. reading string/file dangerous in presence of read macros. setting *read-eval* nil prevents execution. 3. reading need simple. using with-open-file provides simple , safe interface (e.g. if condition (exception) raised, close file properly). in name of input stream associated file. 4. in loop @ each iteration read 1 line. here assume each line proper lisp expression (e.g., number or list). if have expression spanning multiple lines, needs changed. #1= lets remember form follows , #1# insert form. used avoid repetition of (read-line ...) form initial , then statements. read-line directed not throw error if end-of-file reached , return :eof instead. 5. until end-of-file reached... 6. read (convert string lisp data) , collect line read file.
this function returns list of (read lisp data) lines of file. example, if "text.txt" contains
((1 2 3) (4 5 6)) (a b c) (:f :g :h) the read-file of "test.txt" result in:
cl-user> (read-file "test.txt") (((1 2 3) (4 5 6)) (a b c) (:f :g :h)) finally, not use setf unless my-list defined using defvar or defparameter (in case should named *my-list*) or if defined locally using let.
Comments
Post a Comment