Reading a line from a file in GNU Prolog

做~自己de王妃 提交于 2019-12-11 14:08:27

问题


I feel like I'm bashing my head against a wall with something that I assume should be easy. Perhaps my approach is incorrect. I definitely don't feel like I understand the concept behind I/O in Prolog. (Such as: what is the difference between a stream alias and the variable bound by open/3?) But I digress:

How do a read a file line-by-line in GNU Prolog? (So without access to the handy functions that SWI has.) I assume it has something to do with get_char/1 and peek_char/1 (to check for a terminating newline) but my attempts to implement a workable solution have failed so far.

Here is as far as I've gotten:

readl_as_list(ID, X):-
    current_input(ID),
    readl_as_list(X).

readl_as_list([X]):-
    (peek_char(NextChar), ==(NextChar, '\n'); 
        get_code(Char1),
        append([X], [Char1], X),
        readl_as_list(X)).

printl_list([]):-
    !, nl.
printl_list([H|X]):-
    put_code(H), printl_list(X).

Loading this into the interpreter, I get (empty lines removed for readability):

| ?- open('word_list.txt', read, ID).
ID = '$stream'(2)
yes
| ?- readl_as_list(ID, X).
ID = '$stream'(0)
X = [_] ? 
% (interpreter pauses until I press return)
yes
| ?- printl_list(X).
X = []
yes

The lines don't necessarily have to be read in as character lists, but since my goal is to search through a list of words for ones that match certain conditions (no repeat letters, for example), that seemed the most sensible way to do it.


回答1:


I wrote an utility, that fetch a line of codes. Returns end_of_file at end...

read_line_codes(S, SoFar, L) :-
    get_code(S, C),
    (   C == -1
    ->  (  SoFar == []
        ->  L = end_of_file
        ;   reverse(SoFar, L)
        )
    ;   (  C == 0'\n
        -> reverse(SoFar, L)
        ;  read_line_codes(S, [C|SoFar], L)
        )
    ).

test:

?- open('data_grid.pl',read,S),repeat,read_line_codes(S,[],L),format('~s',[L]).
/*  File:    data_grid.pl
S = <stream>(0x335c9e0),
L = [47, 42, 32, 32, 70, 105, 108, 101, 58|...] ;
    Author:  Carlo,,,
S = <stream>(0x335c9e0),
L = [32, 32, 32, 32, 65, 117, 116, 104, 111|...] ;
    Created: Oct 20 2011
S = <stream>(0x335c9e0),
L = [32, 32, 32, 32, 67, 114, 101, 97, 116|...] ;
...


来源:https://stackoverflow.com/questions/13615042/reading-a-line-from-a-file-in-gnu-prolog

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