Previous Up Next

Chapter 14  Strategies

14.1  Retrieving information from trees

Problem:
We want to retrieve all subtrees that are instances of one type.

Solution:
Strategies can browse trees in several ways.

Example:
We seek all chairs in the house.


Here is the %gom datatype definition:
 module House
 imports String 
      
 abstract syntax
      
 House = concRoom(Room*)
 Room = room(name: String, furniture: Furniture)
 Furniture = concPieceOfFurniture(PieceOfFurniture*)
 PieceOfFurniture = bed()
                  | chair()
                  | armchair()
                  | fridge()


Here the corresponding import:
import tutorial.cookbook.house.*;
import tutorial.cookbook.house.types.*;

import tom.library.strategy.mutraveler.MuTraveler;
import tom.library.strategy.mutraveler.Identity;
import jjtraveler.reflective.VisitableVisitor;
import jjtraveler.Visitable;
import jjtraveler.VisitFailure;


Don't forget to include the mutraveler library:
  %include { mutraveler.tom }


We build a House:
 House myHouse = 
   `concRoom(room("kitchen",concPieceOfFurniture(chair(),chair(),fridge())),
             room("bedroom",concPieceOfFurniture(bed(),chair())));


We create a elementary strategy that seeks all chairs in there. This strategy extends `Identity(), because we want to go through even if a failure happens. In other cases, we'd rather use `Fail() to stop if we encounter a failure.
  %strategy SeekChairs() extends `Identity() {
    visit PieceOfFurniture {
      chair() -> { 
        System.out.println("1 Chair !");
      }
      armchair() -> {
        System.out.println("1 Armchair !");
      }
    }
  }


Here we visit the tree using a BottomUp strategy:
try {
  MuTraveler.init(`BottomUp(seekChairs)).visit(myHouse);
} catch (VisitFailure e) {
  System.out.println("failed on = " + myHouse);
}


14.2  Modifying information on trees

Problem:
We want to modify information on trees.

Solution:
We use a strategy that modifies the inspected node.

Example:
We want to replace chairs by armchairs.


To do so, we use a strategy that replaces chairs by armchairs. We use the same datatype definition as in the previous example.
  %strategy ReplaceChairs() extends `Identity() {
    visit PieceOfFurniture {
      chair() -> { return `armchair(); }
    }
  }


Here we browse the tree with a BottomUp strategy:
try {
  myHouse = (House)MuTraveler.init(`BottomUp(replaceChairs)).visit(myHouse);
} catch (VisitFailure e) {
  System.out.println("failed on = " + myHouse);
}



Previous Up Next