Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
06 Java-Prolog Integration
Mirko Viroli mirko.viroli@unibo.it
Ingegneria Due Alma Mater StudiorumUniversit` di Bologna a Cesena a
Academic Year 2006/2007
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Advantages of Prolog
Declarative style of programming Concise way of expressing algorithms and data structures Intrinsic search & re-try mechanisms Navigation abilities Rapid prototyping (More near to model abstract concepts)
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Advantages of Java
Imperative style of programming More easy for the typical programmer More ecient than Prolog Wide availability of libraries Graphics, Network, File-System, XML, . . .
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Why Java-Prolog integration
Mainstream Scenario
Using Java for everything Using Prolog for nothing
The Proposed Scenario
Using Java for standard management and low-level aspects Using Prolog for data & behaviour of the system model
Examples
In a MVC application, the model written in Prolog In writing an agent, modelling its mind in Prolog Sometimes, even accessing Java from Prolog to exploit the
JVM
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
public class C{ public static void main(String[] s){ javax.swing.JFrame f=new javax.swing.JFrame(); f.setSize(100,100); f.setVisible(true); } }
This is a simple case of a Java class that creates a window on
the screen using javax.swing library
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
createframe(Name,X,Y):java_object(javax.swing.JFrame,[],Obj), Obj <- setTitle(Name), Obj <- setSize(X,Y), Obj <- setVisible(true). ?- createFrame(Prova,400,300).
Invoking the above goal causes a similar execution
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Predicate java object/3
Signature
java object(+ClassName,+ArgumentList,-ObjRef) ClassName is the package-qualied name Retrieved through the classpath of the 2P application ArgumentList is a list of arguments for the constructor integers, strings, Java objects (see below) ObjRef is a Prolog term used as Object reference it is of the kind $obj 2 It calls the Java construct of ClassName class, passing
arguments, and the result is associated to handler ObjRef Example ?- java_object(Integer,1,X).
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Predicate <-/2
Signature
ObjRef <- MethName(Args) It calls on ObjRef (obtained through java object) method
MethName, passing Args as arguments
This works if we do not need any result
Example ?- java_object(javax.swing.JFrame,[],Obj), Obj <- setSize(X,Y), Obj <- setVisible(true).
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Predicate returns/2
Signature
ObjRef <- MethName(Args) returns ObjRef2 ObjRef2 unies with the result
Example ?- java_object(javax.swing.JFrame,[],Obj), Obj <- setSize(X,Y), Obj <- setVisible(true), Obj <- isVisible returns Z. Z/true
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Other predicates
Example
To read/write the eld of an object To create/access Java arrays To load a class dynamically ...
Where learning more?
See document developer-guide.pdf in tuProlog
documentation
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
An example application: handling vectors
Want to handle vectors of integers in Prolog
Providing the following predicates
vector new(-VectorRef) vector add(+VectorRef,+Element) vector addall(+VectorRef,+OtherVectorRef) vector clear(+VectorRef) vector contains(+VectorRef,+Element) vector lookup(+VectorRef,+Position,-Element) vector isempty(+VectorRef,+Position,-Element) vector size(+VectorRef,-Size) vector print(+VectorRef)
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Some examples
Code
vector_new(V):-java_object(java.util.Vector,[],V). vector_add(V,E):-java_object(java.lang.Integer,[E],I), V <- add(I). vector_size(V,S):-V <- size returns S. vector_lookup(V,P,E):-V <- elementAt(P) returns E.
Application
?-vector_new(X), vector_add(X,1), vector_add(X,2), vector_lookup(X,0,N).
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
The tuprolog Java library
The approach..
Via an API providing:
Classes representing an engine, a term, a solution Methods to solve goals, ask for other solutions, navigate terms alice.tuprolog
Main Classes
Prolog: a Prolog Virtual Machine Theory: a Prolog DB, as a text or list of clauses SolveInfo: the outcome of a goal Term: the interface to any term
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Direct Goal Solution
Working with the Prolog command-line
import alice.tuprolog.*; public class Test1 { public static void main(String[] args) throws Exception { Prolog engine = new Prolog(); // Note: append is a built-in predicate! SolveInfo info = engine.solve("append([1],[2,3],X)."); System.out.println(info.getSolution()); } }
Result
append([1],[2,3],[1,2,3])
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Getting all solutions
public class Test2 { public static void main(String[] args) throws Exception { Prolog engine = new Prolog(); SolveInfo info = engine.solve("append(X,Y,[1,2,3])."); while (info.isSuccess()){ System.out.println( "solution: "+info.getSolution()+ " - bindings: X/"+info.getTerm("X")+ " Y/"+info.getTerm("Y")); if (engine.hasOpenAlternatives()){ info=engine.solveNext(); } else { break; } } } } solution: solution: solution: solution: append([],[1,2,3],[1,2,3]) - bindings: X/[] Y/[1,2,3] append([1],[2,3],[1,2,3]) - bindings: X/[1] Y/[2,3] append([1,2],[3],[1,2,3]) - bindings: X/[1,2] Y/[3] append([1,2,3],[],[1,2,3]) - bindings: X/[1,2,3] Y/[]
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
The structure of Terms
Term, The root of the hierarchy
Methods:
getRenamedCopy: Changes the name of variables isAtom: Is this a constant name or number? isList: Is this a list? unify: Does this unify with that?
Hierarchy
Term: The root of the hierarchy Var: A variable (with a name of anonymous) Number: int, oat, and so on
Double, Float, Int, Long Struct: a compound term, but also a list
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Creating and Using Terms
public class Test3 { public static void main(String[] args) throws Exception { Prolog engine = new Prolog(); // [1] Term list1=engine.toTerm("[1]"); // [2,3] Term list2=new Struct(new Term[]{new Int(2),new Int(3)}); // append([1],[2,3],X). Term app=new Struct("append",list1,list2,new Var("X")); SolveInfo info = engine.solve(app); System.out.println(info.getSolution()); } }
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Reading Terms
public class Test4 { public static void main(String[] args) throws Exception { Prolog engine = new Prolog(); Term t=new Struct(); // t will be [0,1,2,...,9,10] for (int i=10;i>=0;i--){ t=new Struct(new Int(i),t); } Term app=new Struct("append",t,t,new Var("X")); SolveInfo info = engine.solve(app); Struct t2=(Struct)info.getTerm("X"); for(java.util.Iterator i=t2.listIterator();i.hasNext();){ System.out.println(""+i.next()); } } }
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Setting a Theory
public class Test5 { public static void main(String[] args) throws Exception { Prolog engine = new Prolog(); Theory t=new Theory( "search(E,[E|_])."+"\n"+ "search(E,[_|L]):-search(E,L)."+"\n" ); // engine.setTheory(new FileInputStream("file.pl")); engine.setTheory(t); SolveInfo info = engine.solve("search(1,[1,2,3])."); System.out.println(""+info.getSolution()); } }
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Which applications?
Each time you want in Java something that is better
implemented in Prolog
Example
Realise permutations over Lists
Permutation are easy implemented in Prolog by a predicate
perm(+L,-L2)
Build a Java method that takes a LinkedList and returns a
Iterator<java.util.LinkedList>, each time invoking solveNext() and building the LinkedList from the result.
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Prolog Libraries
What is a Prolog Library?
It is basically a Prolog DB It includes the denition of many predicates It can be loaded in dierent ways: From another theory through goal load library/1 In the 2P IDE through the library manager
Built-in examples
BasicLibrary: Standard operators, e.g. append. ISOLibrary: Standard operators of ISO standard IOLibrary: for Input/Output, e.g. tell, told They are all automatically added by 2P IDE
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Building a Library in Java
It is a very elegant approach
Write a Java class where each method denes a dierent
predicate
Compile this class, e.g. with name lib.mylibrary Load the library with load library(lib.mylibrary)
Structure of methods
public boolean <pred name> <N>(T1 arg1,...,Tn argN) public Term <eval name> <N>(T1 arg1,...,Tn argN) where Ti is either Term, Var, etc.
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
A Simple Library
public class TestLibrary extends Library { // builtin functor sum(A,B) public Term sum_2(Number arg0, Number arg1){ float arg0 = arg0.floatValue(); float arg1 = arg1.floatValue(); return new Float(arg0+arg1); } // builtin predicate println(Message) public boolean println_1(Struct arg){ System.out.println(arg); return true; } } test :- N is sum(5,6), println(N).
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
Projects in Prolog
Building Prolog Libraries in Java
Accessing a DBMS via JDBC Parsing an XML document, and transforming it using XSLT ...
Building Java Applications using Prolog
A game like chess, where the computer is played by Prolog An application where a core is implemented in Prolog ...
Others related to Parsers and Languages
...
Outline On Java-Prolog Integration Prolog calling Java Java calling Prolog Prolog libraries written in Java Projects in Prolog
06 Java-Prolog Integration
Mirko Viroli mirko.viroli@unibo.it
Ingegneria Due Alma Mater StudiorumUniversit` di Bologna a Cesena a
Academic Year 2006/2007