首页 > 解决方案 > 读取文件的一些问题

问题描述

我使用一些序言代码来读取要列出的文件编号,读取工作正常,我不能使用包含已读取编号的列表。

my_representation(Codes, Result) :-

    atom_codes(Result, Codes).

stream_representations(Input, L) :-

    read_line_to_codes(Input, Line),

    (   Line == end_of_file

    ->  L = []

    ;write("stream myrepresant oncesi Line="),writeln(Line),
    write("stream myrepresant oncesi FinalLine="),writeln(FinalLine),      
        my_representation(Line, FinalLine),
        stream_representations(Input, FurtherLines).

main :-
    stream_representations(Input, L),

    close(Input).

标签: prolog

解决方案


实际上,调用stream_representations(Input, L)将变量实例化为Latom '1,2,3,4',如以下查询所示:

?- my_representation([49, 44, 50, 44, 51, 44, 52], L).
L = '1,2,3,4'.

为了获得所需的结果,您可以修改谓词my_representation如下:

my_representation(Codes, Result) :-
    atom_codes(Atom0, Codes),                % obtain Atom0 = '1,2,3,4'
    format(atom(Atom1), '[~w]', Atom0),      % obtain Atom1 = '[1,2,3,4]'
    read_term_from_atom(Atom1, Result, []).  % transform atom '[1,2,3,4]' into list [1,2,3,4]

现在,我们有:

?- my_representation([49, 44, 50, 44, 51, 44, 52], L).
L = [1, 2, 3, 4].

[编辑]

您可以修改您的程序以使用这个新版本的谓词my_representation,如下所示:

main :-
    open('test.txt', read, Input),
    stream_representations(Input, Codes),
    close(Input),
    my_representation(Codes, List),       % <= call new version only here
    writeln('list read': List),
    forall(append(Prefix, Suffix, List),
           writeln(Prefix - Suffix)).

stream_representations(Input, L) :-
    read_line_to_codes(Input, Line),
    (   Line == end_of_file
    ->  L = []
    ;   append(Line, FurtherLines, L),   % <= just append line to further lines
        stream_representations(Input, FurtherLines),
        writeln('Stream represention': L) ).

my_representation(Codes, Result) :-
    atom_codes(Atom0, Codes),
    format(atom(Atom1), '[~w]', Atom0),
    read_term_from_atom(Atom1, Result, []).

结果:

?- main.
Stream represention:[49,44,50,44,51,44,52]
list read:[1,2,3,4]
[]-[1,2,3,4]
[1]-[2,3,4]
[1,2]-[3,4]
[1,2,3]-[4]
[1,2,3,4]-[]
true.

推荐阅读