2016-12-05 28 views
2

我試圖實現一個流 - >文件函數,該函數將字符流打印到文件中。我覺得我接近一個解決方案,但不知道如何完成這一點。球拍計劃 - 將字符流寫入文件

(define stream->file 
    (lambda (filename str) 
    (let ((output (open-output-file filename))) 
     (letrec 
      ((build-output-stream 
      (lambda (str) 
       (let ((char (write-char (stream-first str) output))) 
       (if (eof-object? char) 
        (begin 
         (close-output-port output) 
         empty-stream) 
        (stream-cons char (build-output-stream (stream-rest str)))))))) 
     (build-output-stream str))))) 

在輸出中,除了輸入#<stream>之外,這不起作用。它創建一個文件,但不寫入它。我錯過了什麼?

+0

什麼是您的流?另外,如果我是對的,沒有理由使用'stream-cons'並返回'empty-stream'。返回「輸出」會更有意義。 'letrec'也是無意義的,你可以使用一個命名的let來代替。 –

回答

1

我發現你的代碼過於複雜。你需要寫入流中的每個元素,因爲這是純粹的副作用,你可以使用stream-for-each。由於thunk完成時它將關閉端口,所以不用進行文件端口處理,而是更容易使用with-output-to-file。這是結果:

(define (stream->file file-path stream) 
    (with-output-to-file file-path 
    (thunk (stream-for-each display stream)))) 

(stream->file "test-stream.txt" (stream #\t #\e #\s #\t #\newline)) 
; undefined, makes a file named "test-stream.txt" with the content "test\n"