Prolog
Online Prolog
main.pro is loaded by SWI-Prolog 10.0. There’s no interactive ?- prompt: the program runs the goal you name in :- initialization(main, main). and stops when it finishes. Output isn’t buffered, so a prompt shows before the program reads.
Try it aboveHow Prolog runs here
- Versions
- SWI-Prolog 10.0
- Run
swipl main.pro- Limits per run
- 256 MB memory, 15 s of CPU time on half a core, 2 MB of output
- Time
- Up to 10 minutes a run (30 on a paid plan); waits 2 minutes for input (5 on a paid plan)
- Sandbox
- Each run gets its own Linux sandbox with no network access. Text files your program writes next to your code open as new tabs.
- Good to know
- Runs the goal set with initialization(main, main), then stops.
A Prolog program with facts, rules and input
This main.pro defines a small family tree, reads a name, and collects the answers with findall:
:- initialization(main, main).
parent(ann, bob).
parent(ann, cara).
parent(bob, dan).
parent(cara, eve).
grandparent(X, Z) :- parent(X, Y), parent(Y, Z).
main :-
write('Name: '),
read_line_to_string(user_input, S),
atom_string(Name, S),
findall(C, parent(Name, C), Kids),
format("Children of ~w: ~w~n", [Name, Kids]),
findall(G, grandparent(Name, G), Grand),
format("Grandchildren of ~w: ~w~n", [Name, Grand]).$ swipl main.pro Name: ann Children of ann: [bob,cara] Grandchildren of ann: [dan,eve]
Running goals and reading input
- :- initialization(main, main). runs main/0 once the file is loaded. Without it, the facts load and nothing else happens.
- read_line_to_string(user_input, S) reads a line as a string; atom_string/2 or number_string/2 turn it into an atom or a number.
- read(X) reads a Prolog term and needs a full stop after it, so type foo. rather than foo.
- Arguments from Run settings are in current_prolog_flag(argv, Args).
Errors you’ll see
- “Unknown procedure: greet/1” A predicate that isn’t defined, or defined with a different number of arguments.
- “Syntax error: Operator expected” Usually a missing full stop at the end of a clause, so the next line runs into it.
- “user:main: false” main failed: one of its goals had no solution. Print values with writeln along the way to see which.
Questions
Which Prolog is this?
SWI-Prolog 10.0, loading main.pro.
Can I type queries at a ?- prompt?
No. Put the goals you want to run in main and start it with :- initialization(main, main).
How do I read input in Prolog?
read_line_to_string(user_input, S) for a line of text, or read(X) for a term ending in a full stop. Type the input in the terminal while the program runs.