简体   繁体   中英

How to run prolog queries from within the prolog file in swi-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

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.

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 ; 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
$

dog.pl:

dog(john).
dog(ben).

run :- dog(X), write(X).
% OR:
% :- dog(X), write(X).  
% To print only the first option automatically after consulting.

Then:

$ swipl
1 ?- [dog].
% dog compiled 0.00 sec, 4 clauses
true.

2 ?- run.
john
true ;   # ';' is pressed by the user 
ben
true.

3 ?- 

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