How do I read a text file in LISP?

I have a .txt file like this:

0 
1
2
3
4
5
6
7
8
0
1
2
3
4
5
6
7
8

And i want LISP to read the text file and generate two lists, the first one with the first nine values of the text file and the second one with the next nine values. Like these: List1 = (0 1 2 3 4 5 6 7 8), List2 = (0 1 2 3 4 5 6 7 8). I have these code:

(DEFUN text() 
  (SETQ l NIL)
  (LOOP
   (UNLESS (NULL l) (SETQ LST1 (LIST (READ l)(READ l)(READ l)(READ l)(READ l)(READ l)(READ l)(READ l)(READ l)) 
                          LST2 (LIST (READ l)(READ l)(READ l)(READ l)(READ l)(READ l)(READ l)(READ l)(READ l)) 
                          eb (LST1) em (LST2))
           (CLOSE l) (RETURN (ASTAR LST1 LST2)))
   (SETQ l (OPEN filename :if-does-not-exist nil))))

Upvotes: 2

Views: 1908

Answers (1)

coredump
coredump

Reputation: 38799

  • Don't use SETQ with undeclared global variables, use local bindings with let. Global variables make your code fragile w.r.t. side-effects and clutter the global namespace.
  • Don't copy paste or painfully rewrite the same thing over and over, use a loop
  • Don't call open/close yourself unless necessary, prefer with-open-file.
  • You don't need to write in uppercase

Two nested loops

(defun read-18-lines-of-integers-in-two-lists (file)
  (with-open-file (in file)
    (loop repeat 2
          collect (loop repeat 9
                        collect (parse-integer (read-line in))))))

Example

(read-18-lines-of-integers-in-two-lists #P"/tmp/test")
=> ((0 1 2 3 4 5 6 7 8) (0 1 2 3 4 5 6 7 8))

Upvotes: 10

Related Questions