简体   繁体   中英

How to define a predicate in prolog

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.

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).

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 (ie for storing global data), not for normal programming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM