22.1 Callbacks

Simply stated, predicate functors (boolean functors) are functions which return "true" or "false". In OEChem, these functors are often passed into another function. The functors are then called from inside the second function. This is the concept of a "callback" because the second function provides the argument and "call's back" to the functor which was passed into the function. We've already seen examples of this for the generator methods like GetAtoms and GetBonds. However, you can write your own functions and pass predicates as a function argument.

 1 /**************************************************************
 2  * Copyright 2004,2005,2008 OpenEye Scientific Software, Inc.
 3  *************************************************************/
 4
 5 import openeye.oechem.*;
 6
 7 public class CountFunctors {
 8   private static int Count(OEUnaryAtomPred func, OEMolBase mol) {
 9     int count = 0;
10     for (OEAtomBaseIter aiter=mol.GetAtoms();aiter.hasNext();) {
11       OEAtomBase atom = aiter.next();
12       if (func.constCall(atom)) count++;
13     }
14     return count;
15   }
16   public static void main(String argv[]) {
17     OEMol mol = new OEMol();
18     oechem.OEParseSmiles(mol, "c1c(O)c(O)c(Cl)cc1CCCBr");
19
20     System.out.println("Number of Oxygens "+Count(new OEIsOxygen(), mol));
21     System.out.println("Number of Carbons "+Count(new OEIsCarbon(), mol));
22     System.out.println("Number of Halides "+Count(new OEIsHalide(), mol));
23   }
24 }

Listing:22.1 Using a functor callback

In the example above, the function Count loops over the atom and performs a callback to the predicate functor fcn for each atom. If the predicate returns true, a counter is incremented. The main loop passes three of OEChem's predefined atom predicates to the Count function, allowing the same function to calculate the number atoms in the molecule which satisfy the functor passed to it.