Step 1 of 5 · Reading · ~2 min
Learn
Facts and Rules
In Prolog you declare facts — things known to be true:
:- initialization(main).
parent(tom, bob).
parent(tom, liz).
parent(bob, ann).
parent(bob, pat).
main :-
parent(tom, X),
write(X), nl, fail.
main :- true.
When you query parent(tom, X), Prolog finds every binding that makes the fact match: first X = bob, then X = liz. The trailing fail throws the current solution away, which forces the engine back to the choice point and on to the next matching fact. Once no fact is left the first main clause fails for good, and the second main clause is what stops the whole program from failing.
A period ends a clause — it is not a statement separator
This is the most common way a beginner's file stops compiling. Goals inside one clause are joined with commas, and exactly one period closes the clause:
% CORRECT — one clause, three goals
show :- likes(alice, X), write(X), nl.
% BROKEN — the period after nl ends the clause, so a `true.` written
% underneath it becomes a new clause for the control construct true/0:
% fatal error: redefining control construct true/0
% compilation failed
GNU Prolog refuses the whole file, so you get a compile error rather than a wrong answer. When you turn a commented-out line into real code, delete the leftover true. sitting under it.
Compound terms group data: point(3, 4), book(title('Foundation'), author('Asimov')). The same atom can name a relation (used as a predicate) or a structure (used as a term).
Operators are infix functions: X is 2 + 3 evaluates the right-hand side and binds X to 5. =:= compares numbers. = unifies — a very different thing, and the subject of a later lesson.
Reading stdin depends on the system. This course is graded by GNU Prolog, where read_term(X, []) reads one complete term ended by a period and get_char/1 reads a single character. SWI-Prolog additionally offers read_string/5, which GNU Prolog does not have.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…