Printing all Prolog answers to a file

Prolog lets you specify a series of declarative logic statements (i.e. “X is an Apple”, “if X is an Apple then X is a fruit”). It can trace through all solutions to a problem. In the IDE this is done by pressing “;”. If you structure your program correctly, you can get the whole output to print to a file.

main :- 
	set_prolog_flag(toplevel_print_options,
                [quoted(true)]),
	subset(['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'], X),
	write(X),
        nl,fail;true.
run :- main, halt.

This triggers a loop by failing each output – since the result is always considered a failure, Prolog looks for the next valid result. The first line of main sets output options – this ensures that long values are not truncated with an ellipsis. The second line is your function call. “Write” displays the results to the command line, and nl adds a line break. “Fail” causes the function to be re-evaluated with the next set of parameters, but ultimately main returns “true”, so that anything that calls it can continue on.

Run it like so:

swipl -s test.pl -t run > output.txt

The -s argument specifies a file containing declaration statements. -t specifies a default goal to evaluate.

Tags: , , ,

0 comments ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment

Current day month ye@r *