The Top Level & Your First Program

3.1 The top level (REPL)

Queries end with a period ..

; asks for the next solution; Enter accepts the current one.

true. means success; false. means failure (no (more) solutions).

w/p toggles printing depth; h shows help while answering.

$ swipl
?- X = 5, Y is X * 2.
X = 5,
Y = 10.

?- member(X, [a, b, c]).
X = a ;          % press ; (or space) for more solutions
X = b ;
X = c.

?- halt.         % exit

3.2 Loading a program

Run directly: swipl family.pl.

% Facts
parent(tom, bob).
parent(tom, liz).
parent(bob, ann).
parent(bob, pat).
parent(pat, jim).

male(tom). male(bob). male(jim).
female(liz). female(ann). female(pat).

% Rules
father(X, Y) :- parent(X, Y), male(X).
mother(X, Y) :- parent(X, Y), female(X).
grandparent(X, Z) :- parent(X, Y), parent(Y, Z).
sibling(X, Y) :- parent(P, X), parent(P, Y), X \== Y.
?- [family].                 % consult (load) family.pl
?- consult('family.pl').     % same
?- make.                     % reload modified files
?- father(tom, Who).
Who = bob ;
Who = liz.         % tom is male and is liz's parent, so he is her father too
?- mother(M, jim).
M = pat.

3.3 Hello World

:- Goal. is a directive: executed when the file is loaded.

:- initialization(main, main).

main :-
    format("Hello, World!~n").
swipl hello.pl

3.4 Comments

% Single-line comment
/* Multi-line
   comment */
%! predicate(+Arg) is det.    % PlDoc structured comment

3.5 Useful top-level helpers

show clauses of a predicate help(pred). / apropos(word). trace. / notrace. open source in editor ls., pwd., cd(Dir). timing & inferences memory/time stats