问题描述
我在 Prolog 中编写了一个词法分析器和一个解析器.它将字符串与其 AST 统一起来.这是我正在处理的编译器/解释器项目的一部分.当然,我现在想从文件中读取字符串来解析它.但是,我为此找到的谓词是read,它只读取 Prolog 原子和谓词,就像带有
I have written a lexer and a parser in Prolog. It unifies a string with its AST. This is part for a compiler/interpreter project I am working on. Naturally, I now want to read the string from a file to parse it. However, the predicates I have found for this is read, and it only reads Prolog atoms and predicates, like files with
hello.
我一直在使用 double_quotes 设置,但没有成功.
I have been twiddling with the double_quotes settings, but with no success.
我希望能够读取这样的文件
I want to be able to read a file with something like this
let id = \x.x in id (S (S Z))
然后将此字符串发送到解析谓词.
and then send this string to the parsing predicates.
推荐答案
您可以使用 read_line_to_codes/2
或 read_line_to_codes/3
.一个示例程序,它从 stdin 读取单行并将它们打印到 stdout 如下:
You can use read_line_to_codes/2
or read_line_to_codes/3
. An example program which reads individual lines from stdin and prints them to stdout is the following:
read_lines([H|T]) :-
read_line_to_codes(user_input, H), H \= end_of_file, read_lines(T).
read_lines([]).
write_lines([]).
write_lines([H|T]) :-
writef("%s\n", [H]), write_lines(T).
main :-
read_lines(X), write_lines(X).
(这使用 writef/2
用于打印.)还有 read_stream_to_codes/2
和 read_stream_to_codes/3
,与线条无关.以下代码将所有来自 stdin 的输入一次性打印到 stdout:
(This uses writef/2
for printing.) There are also read_stream_to_codes/2
and read_stream_to_codes/3
, which are not concerned with lines. The following code prints all input from stdin in one go to stdout:
main :-
read_stream_to_codes(user_input, X), writef("%s", [X]).
当然也可以从文件而不是标准输入中读取.有关更多信息,请参阅 readutil
库.
Of course it's also possible to read from a file instead of stdin. For more, see the readutil
library.
这篇关于在 Prolog 中读取字符串(从文件中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!