ファイルへの出力の練習として、
の練習問題2 と3 をやってみた。
練習問題2
ファイルをコピーする関数 (my-copy-file) を書いてください。
(define my-copy-file
(lambda (infile outfile)
(let ((in (open-input-file infile))
(out (open-output-file outfile)))
(let loop ((c (read-char in)))
(if (eof-object? c)
(begin
(close-input-port in)
(close-output-port out))
(begin
(display c out)
(loop (read-char in))))))))
実行例:
^o^ > type sample.txt Hello world! Scheme is an elegant programming language. ^o^ > gosh -I. gosh> (load "my-copy-file.scm") #t gosh> (my-copy-file "sample.txt" "sample.out") #<undef> gosh> (exit) ^o^ > type sample.out Hello world! Scheme is an elegant programming language.
練習問題3
任意個の文字列の引数をとり、それらを標準出力に1行に1つずつ出力する関数 print-lines を書いてください。
(define print-lines
(lambda args
(let loop ((ls args))
(if (pair? ls)
(begin
(display (car ls))
(newline)
(loop (cdr ls)))))))
実行例:
gosh> (load "print-lines.scm") #t gosh> (print-lines "foo" "bar" "baz") foo bar baz #<undef>