projog

6.1. Using Prolog in Java Applications

As well as interacting with Projog using the console application it is also possible to embed Projog in your Java applications. The steps required for applications to interact with Projog are as follows:

Example usage

If your project is configured using Maven then you can add a dependency on Projog by adding the following to your project's pom.xml:

<dependency>
   <groupId>org.projog</groupId>
   <artifactId>projog-core</artifactId>
   <version>0.10.0</version>
</dependency>

Contents of com/example/ProjogExample.java:

package com.example;

import java.io.File;

import org.projog.api.Projog;
import org.projog.api.QueryResult;
import org.projog.api.QueryStatement;
import org.projog.core.term.Atom;

public class ProjogExample {
   public static void main(String[] args) {
      // Create a new Projog instance.
      Projog projog = new Projog();

      // Read Prolog facts and rules from a file to populate the "Projog" instance.
      projog.consultFile(new File("src/main/resources/test.pl"));

      // Execute a query and iterate through all the results.
      QueryResult r1 = projog.executeQuery("test(X,Y).");
      while (r1.next()) {
         System.out.println("X = " + r1.getTerm("X") + " Y = " + r1.getTerm("Y"));
      }

      // Execute a query, set a variable and iterate through all the results.
      QueryStatement s1 = projog.createStatement("test(X,Y).");
      s1.setTerm("X", new Atom("d"));
      QueryResult r2 = s1.executeQuery();
      while (r2.next()) {
         System.out.println("Y = " + r2.getTerm("Y"));
      }

      // Execute a query and iterate through all the results.
      QueryResult r3 = projog.executeQuery("testRule(X).");
      while (r3.next()) {
         System.out.println("X = " + r3.getTerm("X"));
      }

      // Execute a query that uses a conjunction. See: http://projog.org/Conjunction.html
      QueryResult r4 = projog.executeQuery("test(X, Y), Y<3.");
      while (r4.next()) {
         System.out.println("X = " + r4.getTerm("X") + " Y = " + r4.getTerm("Y"));
      }
   }
}

Contents of test.pl:

test(a,1).
test(b,2).
test(c,3).
test(d,4).
test(e,5).
test(f,6).
test(g,7).
test(h,8).
test(i,9).

testRule(X) :- test(X, Y), Y mod 2 =:= 0.

Output of running org.projog.example.ProjogExample:

X = a Y = 1
X = b Y = 2
X = c Y = 3
X = d Y = 4
X = e Y = 5
X = f Y = 6
X = g Y = 7
X = h Y = 8
X = i Y = 9
Y = 4
X = b
X = d
X = f
X = h
X = a Y = 1
X = b Y = 2

See Also