Reading a file in prolog [duplicate]

荒凉一梦 提交于 2019-12-31 02:57:29

问题


Possible Duplicate:
Read a file line by line in Prolog

I found the following prolog code which reads one character at a time and prints out.

process(File) :-
        open('C:/Users/BHARAT/Desktop/a.txt', read, In),
        get_char(In, Char1),
        process_stream(Char1, In),
        close(In).

process_stream(end_of_file, _) :- !.
process_stream(Char, In) :-
        print(Char),
        get_char(In, Char2),
        process_stream(Char2, In).

But if the file has multiple lines is there a way to read 1 whole line at a time so that it will be easy for tokenizing.


回答1:


You say you want to tokenize the input - the best way to do this are definite clause grammars (DCGs). With library(pio) in SWI you can use the grammar directly to read in a file like so:

?- use_module(library(pio)).
?- phrase_from_file(seq(Xs),f).

seq([]) --> [].
seq([E|Es]) --> [E], seq(Es).

Replace now seq//1 by some more elaborate tokenizer.




回答2:


SWI-Prolog has some support predicate, for instance:

..., read_line_to_codes(Stream, Codes), phrase(parse, Codes, []), ...

But I would advise you to adopt phrase_from_file/2 (as already suggested in another answer). There is a support library to help parsing input, with some ready to use parser:

:- use_module(library(http/dcg_basics)).

edit the support library has been renamed, there is a back compatibility trick, that allows old naming, but now it's better to use library(dcg/basics).



来源:https://stackoverflow.com/questions/8231754/reading-a-file-in-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!