Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

prolog - Some problems with reading file

I used some prolog codes for reading file numbers to list, reading is working, i cannot use list that contains readed numbers.

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

question from:https://stackoverflow.com/questions/65647331/some-problems-with-reading-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Actually, the call stream_representations(Input, L) instantiates the variable L to the atom '1,2,3,4', as can be seen with the following query:

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

In order to obtain the desired result, you could modify the predicate my_representation as following:

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]

Now, we have:

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

[EDIT]

You can modify your program to use this new version of the predicate my_representation as following:

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, []).

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...