In this example we load the pengines library and use pengine_create/1
to create a slave pengine in a remote pengine server, and inject a
number of clauses in it. We then use pengine_event_loop/2
to start an event loop that listens for three kinds of event terms.
Running main/0
will write the terms q(a)
, q(b)
and q(c)
to standard output. Using
pengine_ask/3 with the option template(X)
would instead produce the output
a
, b
and c
.
:- use_module(library(pengines)). main :- pengine_create([ server('https://pengines.swi-prolog.org'), src_text(" q(X) :- p(X). p(a). p(b). p(c). ") ]), pengine_event_loop(handle, []). handle(create(ID, _)) :- pengine_ask(ID, q(_X), []). handle(success(_ID, [X], false)) :- writeln(X). handle(success(ID, [X], true)) :- writeln(X), pengine_next(ID, []).
Here is another example, showing how to create and interact with a pengine from JavaScript in a way that seems ideal for Prolog programmers and JavaScript programmers alike. Loading the page brings up the browser's prompt dialog, waits for the user's input, and writes that input in the browser window. If the input was’stop', it stops there, else it repeats. Note that I/O works as expected. All we need to do is to use pengine_input/1 instead of read/1 and pengine_output/1 instead of write/1.
See Also:
<html lang="en"> <head> <title>Pengine Example</title> </head> <body> <h1>Pengine Example</h1> <div id="out"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <script src="https://pengines.swi-prolog.org/pengine/pengines.js"></script> <script type="text/x-prolog"> main :- repeat, pengine_input(X), pengine_output(X), X == stop. </script> <script> var pengine = new Pengine({ oncreate: handleCreate, onprompt: handlePrompt, onoutput: handleOutput }); function handleCreate() { pengine.ask('main'); } function handlePrompt() { pengine.input(prompt(this.data)); } function handleOutput() { $('#out').html(this.data); } </script> </body> </html>
Our third example shows that a non-deterministic predicate can be called remotely by means of pengine_rpc/2, yet behave exactly as if called locally:
?- use_module(library(pengines)). ?- member(X, [a, b, c, d]), pengine_rpc('https://pengines.swi-prolog.org', p(X), [ src_list([p(b), p(c), p(d), p(e)]) ]), member(X, [c, d, e, f]). X = c ; X = d. ?-