A short introduction on how to use the TPL API



This tutorial gives a short introduction on how to use the TPL API. It is recommended, that you read the TPL language reference.

Step 1

Compile the pattern into its AST representation.
TPattern pattern = null;
 try {
  pattern = TPattern.compile("NP << JJ");
 } catch (TPatternSyntaxException pse) {
  // syntax error in pattern
 }

Step 2

Implement the interface tpl.tree.TreeContentProvider according to your needs. Presuming your tree node interface is MyTreeNode.
interface MyTreeNode {
  public List<MyTreeNode> getChildren();
  // ... other methods
 }
 
 .
 .
 .

 // reference to root node
 MyTreeNode myTreeRoot = ...
Then the tpl.tree.TreeContentProvider may be implemented like given below.
TreeContentProvider myContentProvider = new TreeContentProvider() {
  public Object getRoot() {
   return myTreeRoot;
  }

  public Object[] getChildren(Object node) {
   return ((MyTreeNode)node).getChildren().toArray();
  }
 };

Step 3

Create an tpl.tree.IndexedTree using your TreeContentProvider and tpl.tree.DefaultIndexedTree.
Your Ad Here

IndexedTree<MyTreeNode> indexedTree = new DefaultIndexedTree<MyTreeNode>(myContentProvider);

Step 4

Create matcher for the pattern using the indexed tree.
TMatcher<MyTreeNode> matcher = pattern.matcher(indexedTree); 

Step 5

Use the methods getMaps()getTuples() or find() to apply the pattern to the tree.
// returns results as maps, node names are mapped to nodes
 Collection<Map<String, MyTreeNode>> resultMaps = matcher.getMaps();
// returns results as tuples, counted from left to right
 Collection<Collection<MyTreeNode>> resultTuples = matcher.getTuples();
while (matcher.find()) {
  Collection<MyTreeNode> tuple = matcher.getTuple();
  Map<String, MyTreeNode> map = matcher.getMap();
 }

Comments