MIT Scheme 有string->input-port
,Racket 有open-input-string
。如何在纯 Scheme 中实现这一点(没有 Racket、Chicken、Gambit 或任何特定于实现的扩展)。
问问题
243 次
3 回答
1
根据Chis 的回答,我们有一个新的方案标准 R7RS。它open-input-string
提供了。
对于较旧的 R6RS,使用库中的 make-custom-textual-input-port 实现相同的功能很简单(rnrs io ports (6))
。这是我整理的一些东西:
#!r6rs
(import (rnrs base (6))
(rnrs io ports (6))
(rnrs mutable-strings (6))
(rnrs io simple (6)))
(define (open-input-string str)
;; might not be so important to have a different indentifier
;; but this will make debugging easier if implementations use the
;; id provided
(define get-id
(let ((n 0))
(lambda (str)
(set! n (+ n 1))
(string->symbol
(string-append "string-port" str "-"
(number->string n))))))
(let ((len (string-length str))
(pos 0))
(make-custom-textual-input-port
(get-id str)
(lambda (string start count)
(let loop ((cur-dst start)
(cur-src pos)
(n 0))
(cond ((or (>= cur-src len)
(>= n count))
(set! pos cur-src)
n)
(else
(string-set! string cur-dst (string-ref str cur-src))
(loop (+ cur-dst 1)
(+ cur-src 1)
(+ n 1))))))
(lambda () pos)
(lambda (new-pos) (set! pos new-pos))
#f)))
(define test (open-input-string "(1 2 3 4)(5 6 7 8)"))
(define str (read test)) ; str == (1 2 3 4)
(define str2 (read test)) ; str2 == (5 6 7 8)
除了R5RS
使用文件之外,没有办法做到这一点。
于 2013-11-08T16:32:35.407 回答
-2
将字符串写入(临时)文件,然后返回输入端口以将其读回。像这样:
(define (open-input-string string)
(let ((file "/tmp/foo"))
(call-with-output-file file
(lambda (port)
(display string port)))
(open-input-file file)))
> (define ps (open-input-string "This is a test; it is only a test"))
> ps
#<input-port (textual) "/tmp/foo">
> (read-line ps)
"This is a test; it is only a test"
请注意,您需要更复杂地使用file
. 例如,上面的代码只工作一次;它会在第二次调用时因“文件存在”而失败。但以上是对您问题的简单回答。
于 2013-11-08T15:18:09.540 回答