我正在尝试使用read_line_to_codes(Stream,Result)
和atom_codes(String,Result)
。这两个谓词首先从文件中读取一行char代码,然后将此数组转换回字符串。然后我想将所有这些字符串输入到字符串数组中。
我尝试了递归方法,但是如何在开始时实际将实例化实例化为空,以及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).
我期望一种递归方法将行数组作为字符串。
遵循基于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
我在这个问题上感到很困惑。
read_line_to_codes/2
不在其标准库中。要在没有递归的情况下在SWI-Prolog中执行此操作,并获取字符串:
read_string(Stream, _, Str), split_string(Str, "\n", "\n", Lines)
如果你需要别的东西,你需要更好地解释它是什么。