如何将字符串转换为PLT Scheme中的相应代码(不包含该string->input-port
方法)?例如,我想转换这个字符串:
"(1 (0) 1 (0) 0)"
进入这个列表:
'(1 (0) 1 (0) 0)
是否可以在不打开文件的情况下执行此操作?
Scheme 具有read
从输入端口读取 s 表达式的过程,您可以使用string->input-port
. 所以,你可以从一个字符串中读取一个 Scheme 对象
(read (string->input-port "(1 (0) 1 (0) 0)"))
我没有安装 Scheme,所以我只是从参考资料中阅读它并没有实际测试它。
从PLT方案手册:
(open-input-string string [name-v])
创建一个输入端口,从字符串的 UTF-8 编码(参见第 1.2.3 节)中读取字节。可选name-v
参数用作返回端口的名称;默认为'string
.
从comp.lang.scheme上的这个类似问题中,您可以将字符串保存到文件中,然后从中读取。
这可能类似于以下示例代码:
(let ((my-port (open-output-file "Foo")))
(display "(1 (0) 1 (0) 0)" my-port)
(close-output-port my-port))
(let* ((my-port (open-input-file "Foo"))
(answer (read my-port)))
(close-input-port my-port)
answer)
许多方案都在标准输入端口所在的上下文中with-input-from-string str thunk
执行。例如在开局方案中:thunk
str
(with-input-from-string "(foo bar)"
(lambda () (read)))
评估为:
(foo bar)
lambda 是必要的,因为 athunk
应该是一个不带参数的过程。