Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from file Common Lisp [duplicate]

I need to read from a file but I'm having some issues with the code. I've to read i file like this:

1.0 4.5
4.555 6.43
4.0 5
.....
6 3

2 numbers per line separated by #\Space or #\Tab (in the file I can have a big number of lines). The function read must return a list like this:

((1.0 4.5)(4.555 6.43)(4.0 5)...(6 3))

I've tried using with-open-file, read-line and recursion but i'm having issues handling streams etc. to put those element in the list in the right way

(with-open-file (in "foo.lisp"
            :direction :input
            :if-does-not-exist :error)
(myread in))

(defun myread (filename)
(let ((e (read-line filename nil ’eof))))

???

(cons (;;;numbers of current line;;;)(myread (filename)))

How can I do that? thanks

like image 207
Mellow Avatar asked Nov 29 '25 01:11

Mellow


1 Answers

The usual idiom is

(defun read-file-as-lines (filename)
  "Read file into a list of lines."
  (with-open-file (in filename)
    (loop for line = (read-line in nil nil)
      while line
      collect line)))

(defun line-as-list (line)
  "Read all objects from the line as a list."
  (read-from-string (concatenate 'string "(" line ")")))

(mapcar #'line-as-list (read-file-as-lines "mydata"))

If you are concerned with memory use, you can use map-into instead of mapcar or even pass line-as-list as an argument to read-file-as-lines.

Required reading:

  • with-open-file
  • loop
  • read-from-string
  • concatenate

Exercise: use loop in line-as-list instead of prepending and appending parenthesis. This way you can control how many objects you read and handle comments &c.

Solution: string-tokens.

like image 86
sds Avatar answered Dec 01 '25 17:12

sds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!