Advertisement
Guest User

Untitled

a guest
Jul 5th, 2015
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1.  
  2. // Generator class
  3. class Generator
  4. {
  5. var has_value;
  6. var value_holder;
  7. var params;
  8. var func;
  9.  
  10. // empty Generator - no value contained
  11. def Generator() {
  12. this.has_value = false;
  13. this.value_holder = [];
  14. }
  15.  
  16. // continuable generator. on "next_value" call,
  17. // t_func(t_params[0], t_params[1], ..., t_params[n]) is called
  18. def Generator(t_value, Function t_func, Vector t_params) {
  19. this.has_value = true;
  20. this.value_holder = []
  21. this.value_holder.push_back_ref(t_value);
  22. this.params = t_params;
  23. this.func = t_func;
  24. }
  25.  
  26. // internal function used to extract the next value (and store it)
  27. // for later retrieval, and set up the next call
  28. def get_value(Generator g)
  29. {
  30. this.has_value = g.has_value;
  31.  
  32. if (!this.value_holder.empty()) {
  33. this.value_holder.pop_back();
  34. }
  35.  
  36. if (this.has_value) {
  37. this.value_holder.push_back_ref(g.value());
  38. this.func := g.func;
  39. this.params := g.params;
  40. }
  41. }
  42.  
  43. // Returns the held value, if available
  44. def value() {
  45. if (!this.value_holder.empty()) {
  46. return this.value_holder[0];
  47. } else {
  48. throw("No value available")
  49. }
  50. }
  51.  
  52. // calls the generator function and retrieves the next value
  53. def next_value() {
  54. var f = this.func;
  55. var res := call(f, this.params);
  56. this.get_value(res);
  57. }
  58. }
  59.  
  60.  
  61. // Example usage: generate the range [start, end)
  62. def generate_int_range(start, end)
  63. {
  64. if (start != end) {
  65. // return the value 'start' and set up the next call to be 'start + 1'
  66. return Generator(start, `generate_int_range`, [start+1, end]);
  67. } else {
  68. // We're done. Empty generator returned
  69. return Generator();
  70. }
  71. }
  72.  
  73. // TODO Handle cases where there is no result, you simply want to call
  74. // a stateful function repeatedly
  75.  
  76. // Initiate the generator
  77. var g = generate_int_range(1, 10000);
  78.  
  79.  
  80. // Loop through possible results
  81. while (g.has_value)
  82. {
  83. //print(g.value)
  84. g.next_value();
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement