![]() |
![]() |
![]() |
![]() |
![]() |
今回は入出力について説明します。入出力ができればかなり実用的なプログラムを書くことができます。
[code 1]
(define (read-file file-name) (let ((p (open-input-file file-name))) (let loop((ls1 '()) (c (read-char p))) (if (eof-object? c) (begin (close-input-port p) (list->string (reverse ls1))) (loop (cons c ls1) (read-char p))))))たとえば、次のような内容のファイル (C:\doc\hello.txt) を作って試してみると [example 1] のような結果が得られます。 改行文字は '\r\n' で表されるので、少し見にくいのですが、ちゃんと読まれいているのがわかります。 出力用関数 display を使うと整形されます [example 2]。 [hello.txt]
Hello world! Scheme is an elegant programming language.[example 1]
> (current-directory "Z:/doc/scheme") > (current-directory ) #<path:C:\doc\scheme\> > (read-file "hello.txt") "Hello world!\r\nScheme is an elegant programming language.\r\n"[example 2]
> (display (read-file "hello.txt"))
Hello world!
Scheme is an elegant programming language.
[code 2]
(define (read-file file-name) (call-with-input-file file-name (lambda (p) (let loop((ls1 '()) (c (read-char p))) (if (eof-object? c) (begin (close-input-port p) (list->string (reverse ls1))) (loop (cons c ls1) (read-char p)))))))
[code 3]
(define (read-file file-name) (with-input-from-file file-name (lambda () (let loop((ls1 '()) (c (read-char))) (if (eof-object? c) (list->string (reverse ls1)) (loop (cons c ls1) (read-char)))))))
[paren.txt]
'(Hello world! Scheme is an elegant programming language.) '(Lisp is a programming language ready to evolve.)[code 4]
(define (s-read file-name) (with-input-from-file file-name (lambda () (let loop ((ls1 '()) (s (read))) (if (eof-object? s) (reverse ls1) (loop (cons s ls1) (read)))))))paren.txt を [code 4] の関数で読むと、次のようになります。
> (s-read "paren.txt")
((quote (hello world! scheme is an elegant programming language.))
(quote (lisp is a programming language ready to evolve.)))
(read-lines "hello.txt") ⇒ ("Hello world!\r\n" "Scheme is an elegant programming language.\r\n")
(define (group-list ls sep)
(letrec ((iter (lambda (ls0 ls1)
(cond
((null? ls0) (list ls1))
((eqv? (car ls0) sep)
(cons (cons sep ls1) (iter (cdr ls0) '())))
(else (iter (cdr ls0) (cons (car ls0) ls1)))))))
(map reverse (iter ls '()))))
(define (read-lines file-name)
(with-input-from-file file-name
(lambda ()
(let loop((ls1 '()) (c (read-char)))
(if (eof-object? c)
(map list->string (group-list (reverse ls1) #\Newline)) ; *
(loop (cons c ls1) (read-char)))))))
実行例:
> (group-list '(1 4 0 3 7 2 0 9 5 0 0 1 2 3) 0) ((1 4 0) (3 7 2 0) (9 5 0) (0) (1 2 3)) > (read-lines "hello.txt") ("Hello world!\r\n" "Scheme is an elegant programming language.\r\n" "")
(define (my-copy-file from to) (let ((pfr (open-input-file from)) (pto (open-output-file to))) (let loop((c (read-char pfr))) (if (eof-object? c) (begin (close-input-port pfr) (close-output-port pto)) (begin (write-char c pto) (loop (read-char pfr)))))))
(define (print-lines . lines) (let loop((ls0 lines)) (if (pair? ls0) (begin (display (car ls0)) (newline) (loop (cdr ls0))))))
![]() |
![]() |
![]() |
![]() |
![]() |