2016-12-05 89 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"