如何解决是否可以在 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")
""
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。