How to define a predicate in prolog

0 votes
asked Dec 3, 2009 by nathan

I am new to Prolog and I have so far learned how to define a predicate in a file and the run the interpreter to use it. But I would like to know if there is a way to define the predicate at the ?- prompt so that I don't have to switch back and forth.

the way I am doing it now is like this

file defs.pl:

adjacent(1,2).
adjacent(1,3).

in the prolog interpreter:

?- consult('defs.pl').
% defs.pl compiled 0.00 sec, 122 bytes
true.
?- adjacent(1,2).
true.

EDIT maybe I meant how to define 'facts' I'm not sure.

2 Answers

0 votes
answered Dec 3, 2009 by catchmeifyoutry

You can use the assert/1 predicate:

?- assert(adjacent(1,4)).
true

EDIT: By the way, this will not work if you try to combine it with predicates defined in a file. So either define all adjacent/2 predicates in your file, are define them all with assert in the command line.

If you do want to define some of the predicates in the file, and others with assert, then declare in your file that the predicate is dynamic:

% file contents
:- dynamic(adjacent/2).
adjacent(1,2).
adjacent(1,3).
0 votes
answered Dec 4, 2009 by starblue

You can do

?- consult(user).

or

?- [user].

and enter the clauses after that, then terminate the input with the end of file character (Ctrl-D in Linux, could be Ctrl-Z in MS-Windows). This is equivalent to reading a file, see the documentation of consult/1.

assert/1 and retract/1 are intended for predicates that are changed dynamically by the code (i.e. for storing global data), not for normal programming.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...