Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run prolog queries from within the prolog file in swi-prolog?

Tags:

prolog

If I have a prolog file defining the rules, and open it in a prolog terminal in windows, it loads the facts. However, then it shows the ?- prompt for me to manually type something. How can I add code to the file, so that it will actually evaluate those specific statements as if I typed them in?

something like this

dog.pl

dog(john).
dog(ben).

% execute this and output this right away when I open it in the console
dog(X).

Does anyone know how to do this?

Thanks

like image 983
omega Avatar asked May 28 '17 21:05

omega


2 Answers

There is an ISO directive on this purpose (and more): initialization If you have a file, say dog.pl in a folder, with this content

dog(john).
dog(ben).

:- initialization forall(dog(X), writeln(X)).

when you consult the file you get

?- [dog].
john
ben
true.
like image 66
CapelliC Avatar answered Sep 19 '22 17:09

CapelliC


Note that just asserting dog(X). doesn't call dog(X) as a query, but rather attempts to assert is as a fact or rule, which it will do and warn about a singleton variable.

Here's a way to cause the execution the way you're describing (this works for SWI Prolog, but not GNU Prolog):

foo.pl contents:

dog(john).
dog(ben).

% execute this and output this right away when I open it in the console
%  This will write each successful query for dog(X)
:- forall(dog(X), (write(X), nl)).

What this does is write out the result of the dog(X) query, and then force a backtrack, via the false call, back to dog(X) which will find the next solution. This continues until there are no more dog(X) solutions which ultimately fails. The ; true ensures that true is called when dog(X) finally fails so that the entire expression succeeds after writing out all of the successful queries to dog(X).

?- [foo].
john
ben
true.

You could also encapsulate it in a predicate:

start_up :-
    forall(dog(X), (write(X), nl)).

% execute this and output this right away when I open it in the console
:- start_up.

If you want to run the query and then exit, you can remove the :- start_up. from the file and run it from the command line:

$ swipl -l foo.pl -t start_up
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 7.2.3)
Copyright (c) 1990-2015 University of Amsterdam, VU Amsterdam
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.

For help, use ?- help(Topic). or ?- apropos(Word).

john
ben
% halt
$
like image 21
lurker Avatar answered Sep 17 '22 17:09

lurker