2017-05-21 5 views
0

guile 1.8またはguile 2を使用すると、次のコードはEOFを過去数行のように見せています。これが抽出プログラムである大きなプログラムでは、以前に読み込まれたデータが一見破壊されます。私はread-lineを使っているのか、eof-objectを間違ってテストしていますか?これは、発現させる問題について長い数行以上にする必要があるGuile Scheme過去のEOFを読むreadline read

1 
2 
3 
# comment line 
4 
5 
1 
2 
3 
# comment line 
4 
5 
1 
2 
3 
# comment line 
4 
5 

:ここ

(use-modules (ice-9 rdelim)) 

(define f 
    (lambda (p) 
    (let loop ((line (read-line p))) 
     (format #t "line: ~a\n" line) 
     (if (not (eof-object? (peek-char p))) 
     (begin 
     (let ((m (string-match "^[ \t]*#" line))) 
      (if m 
      (begin 
       (format #t "comment: ~a\n" (match:string m)) 
       (loop (read-line p)) 
      ))) 
     (format #t "read next line\n") 
     (loop (read-line p))))))) 

(define main 
    (lambda() 
    (let ((h (open-input-file "test"))) 
     (f h)))) 

は、最小限のサンプルダミー入力ファイルです。コード例の長さについてお詫び申し上げますが、この問題は、コードがこの量の複雑さになっても(わずかながら)発生します。

+0

あなたがコメントを見つけたら反復ごとに_two lines_を読んでいます。解決策を構成する別の方法について私の答えを見てください。 –

答えて

1

私はこの手順の書き直しをお勧めします。ファイルを読み込んでその行をループする正しい方法ではないようです。これを試してください:

(define (f) 
    (let loop ((line (read-line))) 
    (if (not (eof-object? line)) 
     (begin 
      (format #t "line: ~a\n" line) 
      (let ((m (string-match "^[ \t]*#" line))) 
      (if m (format #t "comment: ~a\n" line))) 
      (format #t "read next line\n") 
      (loop (read-line)))))) 

(define (main) 
    (with-input-from-file "test" f)) 

あなたのサンプル入力では、うまくいけば、あなたが期待したものである次の出力は、コンソール上で(main)プリントを呼び出し:主な問題は、あなたという事実であるように思わ

line: 1 
read next line 
line: 2 
read next line 
line: 3 
read next line 
line: # comment line 
comment: # comment line 
read next line 
line: 4 
read next line 
line: 5 
read next line 
line: 1 
read next line 
line: 2 
read next line 
line: 3 
read next line 
line: # comment line 
comment: # comment line 
read next line 
line: 4 
read next line 
line: 5 
read next line 
line: 1 
read next line 
line: 2 
read next line 
line: 3 
read next line 
line: # comment line 
comment: # comment line 
read next line 
line: 4 
read next line 
line: 5 
read next line 
+0

Guile 1.8には、驚くほどの時間がありません。もちろん、それらを書き込むことも、代替ロジックを使用することもできます。 – andro

+0

@andro私はそれを知らなかった。そこには、その固定。それ以外に、これはあなたのために働いたのですか? –

+0

その断片はうまく機能します。しかし、この問題はより微妙なようです。私がやっていることは、パターンマッチのためにラインをチェックし、マッチの計算を行い、次のラインを取得したいという小さなパーサを書くことです。 read-lineで入力を読み取ります。言い換えれば、ある種の「次の」コントロールフォーム。そのようなステートメントを多く追加すると、スキームは予測できないように動作します。このようにループから抜け出して次の繰り返しに戻ることはできませんか? – andro