0

我正在尝试使用read_line_to_codes(Stream,Result)and atom_codes(String,Result)。这两个谓词首先从文件中读取行作为字符代码数组,然后将该数组转换回字符串。然后我想将所有这些字符串输入到字符串数组中。

我尝试了递归方法,但是对于如何在开始时实际将数组实例化为空以及process_the_stream/2.

/*The code which doesn't work.. but the idea is obvious.*/

process_the_stream(Stream,end_of_file):-!.
process_the_stream(Stream,ResultArray):-
        read_line_to_codes(Stream,CodeLine),
        atom_codes(LineAsString,CodeLine),
        append_to_end_of_list(LineAsString,ResultArray,TempList),
        process_the_stream(Stream,TempList).

我希望使用递归方法将行数组作为字符串。

4

2 回答 2

2

遵循基于 Logtalk 的可移植解决方案,您可以将其与大多数 Prolog 编译器(包括 GNU Prolog)一起使用,或适应您自己的代码:

---- processor.lgt ----
:- object(processor).

    :- public(read_file_to_lines/2).

    :- uses(reader, [line_to_codes/2]).

    read_file_to_lines(File, Lines) :-
        open(File, read, Stream),
        line_to_codes(Stream, Codes),
        read_file_to_lines(Codes, Stream, Lines).

    read_file_to_lines(end_of_file, Stream, []) :-
        !,
        close(Stream).
    read_file_to_lines(Codes, Stream, [Line| Lines]) :-
        atom_codes(Line, Codes),
        line_to_codes(Stream, NextCodes),
        read_file_to_lines(NextCodes, Stream, Lines).

:- end_object.
-----------------------

用于测试的示例文件:

------ file.txt -------
abc def ghi
jlk mno pqr
-----------------------

简单测试:

$ gplgt
...

| ?- {library(reader_loader), processor}.
...

| ?- processor::read_file_to_lines('file.txt', Lines).

Lines = ['abc def ghi','jlk mno pqr']

yes
于 2019-03-26T21:10:09.273 回答
0

我对这个问题感到很困惑。

  • 该问题被标记为“gnu-prolog”,但read_line_to_codes/2不在其标准库中。
  • 你谈论字符串:你是什么意思?您能否说明 GNU-Prolog或SWI-Prolog 中的哪一个类型测试谓词应该在这些“字符串”上成功?
  • 期望使用递归方法。这意味着什么?你想要一种递归方法,你必须使用递归方法,或者你认为如果你这样做了,你最终会得到一种递归方法?

要在 SWI-Prolog 中执行此操作而无需递归,并获取字符串

read_string(Stream, _, Str), split_string(Str, "\n", "\n", Lines)

如果你需要别的东西,你需要更好地解释它是什么。

于 2019-03-27T08:01:27.000 回答