是否可以在 Scheme R6RS 中有效地从磁盘加载整个文件?

问题描述

以下 get_file 函数从磁盘读取文件作为 Scheme r6rs 字符串:

; Gets all characters from a port
(define (read_chars_from_port_rev port result)
  (let ((char (read-char port)))
    (if (eof-object? char)
      result
      (read_chars_from_port_rev port (cons char result)))))

; Gets the contents of a file as a string
; If it doesn't exist,returns empty
(define (get_file file)
  (if (file-exists? file)
    (let ((port (open-input-file file)))
      (let ((text (list->string (reverse (read_chars_from_port_rev port '())))))
        (begin
          (close-input-port port)
          text)))
    ""))

它的工作原理是打开文件,尾调用递归地逐个字符读入链表,直到找到 eof,关闭文件,然后反转链表(因为尾调用)并转换它到一个字符串。

与 Node.js 的 readFile 相比,这个过程应该很慢,因为它逐个字符读取,并为文件中的每个字符分配一个包含一个单元格的链表。理想情况下,我们应该能够将文件作为字符串缓冲区读取,而无需动态内存分配。

有没有办法用 r6rs 中可用的原语来优化 get_file

解决方法

您可以使用get-string-all

> (let* ((fp (open-input-file "my-file.txt"))
         (buf (get-string-all fp)))
    (close-port fp)
    (display buf))
Four score and seven years ago
our fathers brought forth upon this continent,....

使用 call-with-input-file 可以使这更方便一些:

;;; Returns a string containing the contents of the file `fname`; closes the
;;; input port automatically (unless `get-string-all` does not return for
;;; some reason).
(define (get-file fname)
  (call-with-input-file fname get-string-all))
> (get-file "my-file.txt")
"Four score and seven years ago\nour fathers brought forth upon this continent,....\n"

您可以使用 guard 在查找的文件不存在时方便地返回空字符串(如发布的代码中所示):

(define (guarded-get-file fname)
  (guard (con
          ((i/o-file-does-not-exist-error? con) ""))
    (call-with-input-file fname get-string-all)))
> (guarded-get-file "my-file.txt")
"Four score and seven years ago\nour fathers brought forth upon this continent,....\n"

> (guarded-get-file "oops.txt")
""