|
|
|
This example illustrates the use of the sequence primitive. During one instant, one puts atomic actions (print actions in this case) in sequence.
Source: Short_Sequence.javaimport inria.meije.rc.sugarcubes.*; public class Short_Sequence { public static void main(final String[] args){ final Program p = SC.seq( SC.println("Hello World!") , SC.print("This program shows ") , SC.printError("sequences ") , SC.print("of printed ") , SC.printlnError("messages!") ); final Machine machine = SC.emptyMachine(p); // One uses the run method on the reactive machine which makes the machine react // cyclically until the whole program has finished. The run method then stops // and the reactive machine is then no more useable. In our case only one // reaction is computed. machine.run(); } }
A reactive Machine in SugarCubes also implements the Runnable intefarce of standard Java. So it implements a run method which cyclically makes the reactive machine react until the whole program it contains has completed its execution. So one can call directly the method run of a machine make the system react. One can also use a machine directly has a parameter for a new Thread. So the thread will handle reaction until the end of the program in the reactive machine.
final Thread t = new Thread(SC.emptyMachine()); t.start();The thread will end when the reactive machine ends. One can use the method displayPrompt to enable or disable the automatic display of a prompt at each instant. For example to deactivate the instant prompt during the excution of the run method (it is only effective in the run method) one could use:
machine.displayPrompt(false);
javac -classpath SugarCubesv4.0.0a4.jar Short_Sequence.java
java -classpath SugarCubesv4.0.0a4.jar:. Short_Sequence
One should get the following result:
1-: Hello World! This program shows sequences of printed messages!
The Junior interface of SugarCubes only provides binary sequence primitive. So to compose large sequences one has to build a tree of binary sequence.
Source: Junior_Short_Sequence.javaimport junior.*; public class Junior_Short_Sequence { public static void main(final String[] args){ // The Junior interface of SugarCubes only provides binary sequence primitive. final Program print = Jr.Seq( Jr.Print("Hello World!\n") ,Jr.Seq( Jr.Print("This program shows ") ,Jr.Seq( Jr.Print("sequences ") ,Jr.Seq( Jr.Print("of printed ") ,Jr.Print("messages!\n") ) ) ) ); final Machine machine = Jr.Machine(Jr.Nothing()); machine.add(print); int i = 1; do{ System.out.println("instant "+(i++)+": "); } while(!machine.react()); } }
javac -classpath SugarCubesv4.0.0a4.jar Junior_Short_Sequence.java
java -classpath SugarCubesv4.0.0a4.jar:. Junior_Short_Sequence