views:

287

answers:

1

I have written a lexer and a parser in Prolog. It unifies a string with its AST. This is part for a compiler/interpreter project I am working on. Naturally, I now want to read the string from a file to parse it. However, the predicates I have found for this is read, and it only reads Prolog atoms and predicates, like files with

hello.

I have been twiddling with the double_quotes settings, but with no success.

I want to be able to read a file with something like this

let id = \x.x in id (S (S Z))

and then send this string to the parsing predicates.

+4  A: 

You can use read_line_to_codes/2 or read_line_to_codes/3. An example program which reads individual lines from stdin and prints them to stdout is the following:

read_lines([H|T]) :-
  read_line_to_codes(user_input, H), H \= end_of_file, read_lines(T).
read_lines([]).

write_lines([]).
write_lines([H|T]) :-
  writef("%s\n", [H]), write_lines(T).

main :-
  read_lines(X), write_lines(X).

(This uses writef/2 for printing.) There are also read_stream_to_codes/2 and read_stream_to_codes/3, which are not concerned with lines. The following code prints all input from stdin in one go to stdout:

main :-
  read_stream_to_codes(user_input, X), writef("%s", [X]).

Of course it's also possible to read from a file instead of stdin. For more, see the readutil library.

Stephan202
Thanks :) This was exactly what I was looking for!
Dan