从Scheme(MIT / GNU Scheme)中的文件中读取行

问题描述 投票:1回答:1

我正在尝试Scheme(MIT / GNU Scheme 9.1),我正在编写一些简单的程序来读写文件。

为了将文件中包含的所有行读入列表,我写了以下内容:

(define read-lines-from-port-impl
        (lambda (file-input-port)
                (let* ((line (read-line file-input-port))
                      )
                      (if (eof-object? line)
                          (list)
                          (cons line (read-lines-from-port-impl file-input-port))
                      )
                )
        )
)


(define read-lines-from-port
        (lambda (file-port)
                (if (input-port? file-port)
                    (read-lines-from-port-impl file-port)
                    (list)
                )
        )
)


(define read-lines-from-file
        (lambda (filename)
                (call-with-input-file filename read-lines-from-port)
        )
)

问题1

这似乎有效,但也许在Scheme中有更惯用/更简洁的方法。你能建议如何改进这段代码吗?

问题2

在上面的代码中,我使用了call-with-input-file,它负责在调用read-lines-from-port之前打开一个输入端口,并在该过程完成后关闭它。

如果我想使用open-input-file和close-input-port打开和关闭输入端口,我将如何在Scheme中编写它?我的意思是我必须这样做

  • 调用open-input-file
  • 从结果端口读取行
  • 调用close-input-port

在Haskell中我会使用do notation,但是如何在Scheme中指定这样的一系列动作?

functional-programming scheme
1个回答
2
投票

我没有测试这段代码,但即使我出错了,你也应该从这里弄清楚:

; read-lines [port-or-filename] -- defaults to current input
(define (read-lines . args)
  (let ((p (cond ((null? args) (current-input-port))
                 ((port? (car args)) (car args))
                 ((string? (car args)) (open-input-file (car args)))
                 (else (error 'read-lines "bad argument")))))
    (let loop ((line (read-line p)) (lines (list)))
      (if (eof-object? line)
          (begin (if (and (pair? args) (string? (car args)))
                   (close-input-port p))
                 (reverse lines))
          (loop (read-line p) (cons line lines))))))

您使用begin编写一系列语句,如上所示。

© www.soinside.com 2019 - 2024. All rights reserved.