2017-05-21 49 views
0

使用guile 1.8或guile 2,下面的代碼讀取過去的EOF,看起來是多餘的一行,然後停止。這是一個提取的大型程序所產生的效果是看似腐敗了以前讀取的數據。我是否正確使用read-line或測試eof-object?通過EOF的Guile Scheme讀線讀取

(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)))) 

下面是一個最小的樣品虛擬輸入文件:

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

它需要比渴望體現該問題的幾行。對代碼示例的長度抱歉,但只有在代碼達到這種複雜程度(儘管很小)時纔會出現問題。

+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

該片段正常工作。但這個問題似乎更加微妙。我正在做的是編寫一個小的解析器,它檢查模式匹配的行,對匹配執行一些計算,然後我想獲得下一行,我嘗試通過再次調用循環來嘗試執行,並使用由用讀線讀取輸入。換句話說,就是一種'下一個'控制形式。當我添加很多這樣的陳述時,方案的行爲是不可預測的。難道人們不能擺脫循環並以這種方式回到下一次迭代? – andro