challenge 条件を満たす行を取り除く

ファイルから1行ずつ読み込み、"#"で始まる行だけを取り除いてファイルに出力するコードを書いてください。

サンプル入力

hello!
# remove this
 # don't remove this
bye!
サンプル出力
hello!
 # don't remove this
bye!

Posted feedbacks - Common Lisp

使用例: (erase-commen-out-line 入力ファイル 出力ファイル)
1
2
3
4
5
6
7
8
9
(defun erase-comment-out-line (infile outfile)
  (with-open-file (in infile :direction :input)
    (with-open-file (out outfile :direction :output
					    :if-exists :supersede)
      (do ((line (read-line in nil 'eof)
		 (read-line in nil 'eof)))
	  ((eql line 'eof) 'Done)
	(unless (equal (schar line 0) #\#)
	  (write-line line out))))))

Common Lispで初めてfile入出力書いてみたw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
(require :iterate)
(in-package :iter)
(defun remove-comments (in out)
  (iter (for line in-stream in using #'read-line)
        (unless (char= (aref line 0) #\#)
          (write-line line out))))

(defun test ()
  (with-open-file (in "10.input" :direction :input)
    (with-open-file (out "10.output" :direction :output :if-exists :supersede)
      (remove-comments in out))))

(test)

series を使ってみました。 series はレイジーリストみたいな性質があるので、こういう書き方でも1行ずつ処理されます。

1
2
3
4
5
6
7
8
9
(require :series)

(defun remove-#-line (in-file out-file)
  (let* ((in (series:scan-file in-file #'read-line))
         (lines (series:choose-if
                 #'(lambda (x)
                     (or (string= "" x) (string/= "#" x :end2 1)))
                 in)))
    (series:collect-file out-file lines #'write-line)))

Index

Feed

Other

Link

Pathtraq

loading...