Read a file line by line in Prolog

后端 未结 3 2005

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:57

    In SWI-Prolog, the cleanest solution is to write a DCG that describes what a "line" is, then call a predicate for each line. Use library(pio) to apply the DCG to a file.

    EDIT: As requested, consider:

    :- use_module(library(pio)).
    
    lines([])           --> call(eos), !.
    lines([Line|Lines]) --> line(Line), lines(Lines).
    
    eos([], []).
    
    line([])     --> ( "\n" ; call(eos) ), !.
    line([L|Ls]) --> [L], line(Ls).
    

    Sample usage: ?- phrase_from_file(lines(Ls), 'your_file.txt').

提交回复
热议问题