[plt-scheme] input from file

From: David J. Neu (djneu at att.net)
Date: Sat Apr 3 09:17:34 EST 2004

Markus,

I blew away your original post so I copied it below.

There are many other ways to do what you want, but here's what I do:

;; To split a string use regexp-split as shown below
> (require (lib "string.ss" "mzlib"))
> (define ls (regexp-split " " "dog cat boat"))
> (for-each (lambda (x) (display x) (newline)) ls)
dog
cat
boat

;; To read from a file "line-by-line"
(call-with-input-file "my-input-file.txt"
  (lambda (aport)
    (let loop ((lline (read-line aport 'return)))
      (when (not (eof-object? lline))
        (display lline)
        (newline)
        (loop (read aport))))))

--David


----- ----- ----- ----- ----- ----- ----- ----- ----- ----- 
Oringal post from:
Markus Spath  mspath at arcor.de
Sat, 03 Apr 2004 13:26:07 +0200

hi,

I need some help reading data from a file.

currently I'm hardcoding data-strucures I want to deal with:

--
;; struct question
;; name is a symbol; v1, v2 are numbers
(define-struct question (name v1 v2))

;; questions-hardcoded: -> list of questions
;; generates a list of questions
(define (questions-hardcoded)
   (list
    (make-question 'q1 10 20)
    (make-question 'q2 5 13)
    (make-question 'q3 5 8)
    ...))

(define questions (questions-hardcoded))
--

It would be nice to have a function that builds a list of questions from 
a file, like:

--
;; questions-from-file: string -> list of questions
;; generates a list of questions from a file
(define (questions-from-file filename)
   ... )

(define questions2 (questions-from-file "C:\\home\\scheme\\data.txt"))
--

data.txt:
--
q1 10 20
q2 5 13
q3 5 8
...
--



I've just started recently to teach myself scheme via htdp/DrScheme and 
all examples for I/O I found in the help-desk or via google use 
syntactic constructs I don't know yet; an idiot-proof and minimalistic 
example of how to read a file line by line and how to tokenize a string 
(at whitespace) into symbols and/or numbers would be of great help.

TIA,
markus


Posted on the users mailing list.