Αρχείο κατηγορίας windows batch file

Querying Prolog from Java

This blog entry is for those who want to use Prolog queries from their Java program. I use swi-prolog, a free implementation of the Prolog language.

The SWI-prolog installation includes the java jpl7 package (in the lib installation folder):
http://jpl7.org/JavaApiOverview.jsp

To use it from java you need to setup some system variables before executing your app. Moreover, the java and swi-prolog installations must both be 32 bit or 64bit. For example you can edit a run.bat batch file with the following commands (assuming that swi-prolog is installed in c:/program files/swipl and your app is in the executable <your jar name>.jar file):

  set SWI_PROLOG_PATH=c:\program files\swipl
  set path=%path%;%SWI_PROLOG_PATH%\bin\;%SWI_PROLOG_PATH%\lib\
  swipl.exe --dump-runtime-variables=cmd > plvars.bat
  call plvars.bat
  java -jar <your jar name>.jar

This approach assumes that the jpl.jar library file is included in your jar file, otherwise you must add the jpl.jar to the classpath variable. In the next blog entry I explain how to do that using eclipse.

See an example that adds in the fact father(john,nikos) to the prolog database and then runs the query father(X,nikos):

  
import java.util.Map;
import org.jpl7.*;

public class TestPrologInterface {

  public static void main(String[] args) {
    String s = "assert(father(john,nikos)).";
    Query q = new Query(s);
    // run the query
    if (q.hasNext()) {
      // now I can ask for the father of nikos
      s = "father(X,nikos).";
      q = new Query(s);
      // run the query, repeat while there are more results
      while (q.hasNext()){
        //get a mapping of variables to instantiations:
	Map<String, Term> map = q.next();
	//get the instance of variable X
	String varX = map.get("X").toString();
	//print variable instance
	System.out.println(varX);
      }
    }
  }
}