简体   繁体   English

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

[英]Reading a string (from a file) in Prolog

I have written a lexer and a parser in Prolog. 我在Prolog中编写了词法分析器和解析器。 It unifies a string with its AST. 它通过其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 但是,我为此找到的谓词为read ,并且它仅读取Prolog原子和谓词,例如带有

hello.

I have been twiddling with the double_quotes settings, but with no success. 我一直在搅动double_quotes设置,但没有成功。

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. 然后将此字符串发送到解析谓词。

You can use read_line_to_codes/2 or read_line_to_codes/3 . 您可以使用read_line_to_codes/2read_line_to_codes/3 An example program which reads individual lines from stdin and prints them to stdout is the following: 下面是一个示例程序,该程序从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).

(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. (这使用writef/2进行打印。)还有read_stream_to_codes/2read_stream_to_codes/3 ,它们与行无关。 The following code prints all input from stdin in one go to stdout: 以下代码将所有来自stdin的输入一次打印到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. 当然,也可以从文件中读取而不是从stdin中读取。 For more, see the readutil library. 有关更多信息,请参见readutil库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM