練習:ファイルからの入力

ファイルからの入力の練習。

 cf. 9. 入出力 – もうひとつの Scheme 入門

の練習問題1。

ファイルの内容を1行ずつのリストにして返す関数 read-lines を書いてください。 hello.txt に適用すると次のようになるようにして下さい。’\n’ は #\Newline です。 改行文字は残すようにしてください。

(read-lines “hello.txt”) ⇒ (“Hello world!\r\n” “Scheme is an elegant programming language.\r\n”)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
(define read-lines
(lambda (file-name)
(let ((p (open-input-file file-name)))
(let loop ((lines '()) (line '()) (c (read-char p)))
(cond
((eof-object? c)
(begin
(close-input-port p)
(reverse lines)))
((eq? c #\Newline) (loop (cons (list->string (reverse (cons c line))) lines) '() (read-char p)))
(else (loop lines (cons c line) (read-char p))))))))
(define read-lines (lambda (file-name) (let ((p (open-input-file file-name))) (let loop ((lines '()) (line '()) (c (read-char p))) (cond ((eof-object? c) (begin (close-input-port p) (reverse lines))) ((eq? c #\Newline) (loop (cons (list->string (reverse (cons c line))) lines) '() (read-char p))) (else (loop lines (cons c line) (read-char p))))))))
(define read-lines
  (lambda (file-name)
    (let ((p (open-input-file file-name)))
      (let loop ((lines '()) (line '()) (c (read-char p)))
        (cond
          ((eof-object? c)
           (begin
             (close-input-port p)
             (reverse lines)))
          ((eq? c #\Newline) (loop (cons (list->string (reverse (cons c line))) lines) '() (read-char p)))
          (else (loop lines (cons c line) (read-char p))))))))

実行例:

^o^ > gosh -I.
gosh> (load "read-lines.scm")
#t
gosh> (read-lines "sample.txt")
("Hello world!\r\n" "Scheme is an elegant programming language.\r\n")

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください