在 Prolog 中(从文件中)读取字符串

发布于 2024-08-13 06:32:57 字数 345 浏览 3 评论 0原文

我用 Prolog 编写了一个词法分析器和一个解析器。它将字符串与其 AST 统一起来。这是我正在从事的编译器/解释器项目的一部分。当然,我现在想从文件中读取字符串来解析它。然而,我为此找到的谓词是read,它只读取Prolog原子和谓词,就像

hello.

我一直在用double_quotes设置摆弄的文件一样,但没有成功。

我希望能够读取具有类似内容的文件

let id = \x.x in id (S (S Z))

,然后将该字符串发送到解析谓词。

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小清晰的声音 2024-08-20 06:32:57

您可以使用 read_line_to_codes/2read_line_to_codes/3。一个示例程序,它从 stdin 读取各个行并将其打印到 stdout 如下:(

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/2read_stream_to_codes/3,与行无关。以下代码将 stdin 的所有输入一次性打印到 stdout:

main :-
  read_stream_to_codes(user_input, X), writef("%s", [X]).

当然,也可以从文件而不是 stdin 读取。有关详细信息,请参阅readutil 库。

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).

(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]).

Of course it's also possible to read from a file instead of stdin. For more, see the readutil library.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文