Search code examples
prologswi-prologdcg

Read entire text file into a Prolog variable


I am having the hardest time figuring this out, even though it is one of the simplest things to do in other languages: Is there a simple way to read the entire contents of a text file into a Prolog variable?


Solution

  • Simply state with a DCG what you want to describe, and use library(pio) to parse from a file:

    :- use_module(library(pio)).
    
    all([])     --> [].
    all([L|Ls]) --> [L], all(Ls).
    

    Example:

    ?- once(phrase_from_file(all(Ls), 'all.pl')).
    Ls = [10, 58, 45, 32, 117, 115, 101, 95, 109|...].