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?
Asked
Active
Viewed 1,352 times
2 Answers
6
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|...].

mat
- 40,498
- 3
- 51
- 78
-
Thank you! This did the trick for me. I had seen discussions of using DCG's for arbitrary input, but could not make the connection to how this could be used to read in an arbitrary file. – sdesciencelover Jun 19 '12 at 21:00
-
@sdesciencelover: The big advantage of `library(pio)` will only show, if you do the processing already with the nonterminal. `phrase_from_file/2` does not read the entire file content in one fell swoop but does some internal buffering: In this manner files of abiritrary size can be processed in constant space. – false Jun 23 '12 at 14:51
-
why once/1? Ideally, SWI should detect determinism. Consider to use call_semidet/1: http://stackoverflow.com/questions/12939794/stack-overflow-in-prolog-dcg-grammar-rule-how-to-handle-large-lists-efficiently/12942551#12942551 – false Oct 11 '13 at 15:17
3
in library(readutil) there are some built ins: see read_file_to_codes or read_file_to_terms

CapelliC
- 59,646
- 5
- 47
- 90