Guest User

Untitled

a guest
Oct 20th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. package org.hybird.continuation;
  2.  
  3. import java.util.Iterator;
  4.  
  5. import org.hybird.generator.Generator;
  6.  
  7. public class ContinuationTest
  8. {
  9. public static void main (String [] args)
  10. {
  11. // full read
  12. for (String s : new ExampleGenerator())
  13. {
  14. System.out.println (s);
  15. }
  16.  
  17. // reading 3 out of 4 values
  18. System.out.println ("");
  19. Iterator<String> i = new ExampleGenerator().iterator ();
  20. for (int x = 0; x < 3 && i.hasNext (); ++x)
  21. System.out.println (x + ": '" + i.next () + "'");
  22.  
  23. // generators filtering other generators
  24. System.out.println ("");
  25. for (int even : new EvenNumbersGenerator (new RangeGenerator (10)))
  26. {
  27. System.out.println (even);
  28. }
  29. }
  30.  
  31. @Continuation
  32. private static class ExampleGenerator extends Generator<String>
  33. {
  34. @Override
  35. protected void run ()
  36. {
  37. yield ("1");
  38. yield ("2");
  39. yield ("3");
  40. yield ("4");
  41. }
  42. }
  43.  
  44. @Continuation
  45. public static final class EvenNumbersGenerator extends Generator<Integer>
  46. {
  47. private RangeGenerator generator;
  48.  
  49. public EvenNumbersGenerator (RangeGenerator generator)
  50. {
  51. this.generator = generator;
  52. }
  53.  
  54. @Override
  55. protected void run ()
  56. {
  57. for (int i : generator)
  58. {
  59. if (i % 2 == 0)
  60. yield (i);
  61. }
  62. }
  63. }
  64.  
  65. @Continuation
  66. public static final class RangeGenerator extends Generator<Integer>
  67. {
  68. private int to;
  69.  
  70. public RangeGenerator (int to)
  71. {
  72. this.to = to;
  73. }
  74.  
  75. @Override
  76. protected void run ()
  77. {
  78. for (int i = 0; i < to; i++)
  79. yield (i);
  80. }
  81. }
  82.  
  83. @Continuation
  84. public static class FibonnaciGenerator extends Generator<Integer>
  85. {
  86. private int to;
  87.  
  88. public FibonnaciGenerator (int to)
  89. {
  90. this.to = to;
  91. }
  92.  
  93. @Override
  94. protected void run ()
  95. {
  96. int a = 0;
  97. int b = 1;
  98.  
  99. while (a < to)
  100. {
  101. yield (a);
  102.  
  103. int next = a + b;
  104. a = b;
  105. b = next;
  106. }
  107. }
  108. }
  109. }
Add Comment
Please, Sign In to add comment