Read a file line by line in Prolog

后端 未结 3 2009

I\'d like to read a plain text file and apply a predicate to each line (the predicates contain write which does the output). How would I do that?

3条回答
  •  时光说笑
    2020-11-29 09:42

    There are kind of more possible in number and more reasonable in performance solutions, to get uninterpreted i.e plain text lines from a file:

    SWI-Prolog:

    read_line(S, X) :- 
       read_line_to_codes(S, L), 
       read_line2(L, X).
    
    read_line2(end_of_file, _) :- !, fail.
    read_line2(L, X) :-
       atom_codes(X, L).
    

    Jekejeke Prolog:

    :- use_module(library(stream/console)).
    

    Here are some timings, reading a file of 655 lines:

    test :-
       open('', read, Stream),
       test(Stream),
       close(Stream).
    
    test(Stream) :-
       read_line(Stream, _), !,
       test(Stream).
    test(_).
    

    SWI-Prolog:

    ̀?- time((between(1,100,_), test, fail; true)).
    % 328,300 inferences, 0.125 CPU in 0.143 seconds (88% CPU, 2626400 Lips)
    true.
    

    Jekejeke Prolog:

    ?- time((between(1,100,_), test, fail; true)).
    % Up 121 ms, GC 2 ms, Thread Cpu 94 ms (Current 05/07/19 17:19:05)
    Yes
    

    I guess a SWI-Prolog solution that reads into a string instead into an atom could be faster. But in the above we compare atom against atom reading.

提交回复
热议问题