The following is a Java version of the train
example.
See Train, for information about how the train.sav
file is
created.
This code demonstrates the use of Jasper in single threaded mode. In
this mode only one thread can access the SICStus runtime via a
SICStus
object.
import se.sics.jasper.SICStus; import se.sics.jasper.Query; import java.util.HashMap; public class Simple { public static void main(String argv[]) { SICStus sp; Query query; HashMap WayMap = new HashMap(); try { sp = new SICStus(argv,null); sp.restore("train.sav"); query = sp.openPrologQuery("connected('Orebro', 'Stockholm', Way, Way).", WayMap); try { while (query.nextSolution()) { System.out.println(WayMap); } } finally { query.close(); } } catch ( Exception e ) { e.printStackTrace(); } } }
It is assumed that the reader has read the section on Getting Started, which describes how to get the basics up and running.
This is how the example works:
SICStus
class. Each SICStus object correspond to one independent copy of the
SICStus run-time system (a rather heavy-weight entity).
In this example, we have specified null
as the second argument to
SICStus
. This instructs SICStus to search for sprt.sav
using its own internal methods, or using a path specified by passing
-Dsicstus.path=[...]
to the JVM.
query
. The arguments to this
method are a string specifying a Prolog goal, and a Map
which
will contain a mapping of variable names to bindings. This method is
for finding a single solution.
Note that the string is read by the Prolog reader, so it must conform
to the syntax rules for Prolog, including the terminating period.
There are two more methods for making queries: queryCutFail
,
for side-effects only, and openQuery
to produce several
solutions through backtracking.
restore
. Corresponds to SP_restore()
in the
C-interface. See Loading Prolog Code. Note that this method must
be called before any other SICStus method is called. See the HTML
Jasper documentation for details.
openQuery
method returns a reference to a query, an object
implementing the Query
interface. To obtain solutions, the method
nextSolution
is called with no arguments. nextSolution
returns true
as long as there are more solutions, and the example
above will print the value of the Map WayMap
until there are no
more solutions. Note that the query must be closed, even if
nextSolution
has indicated that there are no more solutions.