Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Generator class
- class Generator
- {
- var has_value;
- var value_holder;
- var params;
- var func;
- // empty Generator - no value contained
- def Generator() {
- this.has_value = false;
- this.value_holder = [];
- }
- // continuable generator. on "next_value" call,
- // t_func(t_params[0], t_params[1], ..., t_params[n]) is called
- def Generator(t_value, Function t_func, Vector t_params) {
- this.has_value = true;
- this.value_holder = []
- this.value_holder.push_back_ref(t_value);
- this.params = t_params;
- this.func = t_func;
- }
- // internal function used to extract the next value (and store it)
- // for later retrieval, and set up the next call
- def get_value(Generator g)
- {
- this.has_value = g.has_value;
- if (!this.value_holder.empty()) {
- this.value_holder.pop_back();
- }
- if (this.has_value) {
- this.value_holder.push_back_ref(g.value());
- this.func := g.func;
- this.params := g.params;
- }
- }
- // Returns the held value, if available
- def value() {
- if (!this.value_holder.empty()) {
- return this.value_holder[0];
- } else {
- throw("No value available")
- }
- }
- // calls the generator function and retrieves the next value
- def next_value() {
- var f = this.func;
- var res := call(f, this.params);
- this.get_value(res);
- }
- }
- // Example usage: generate the range [start, end)
- def generate_int_range(start, end)
- {
- if (start != end) {
- // return the value 'start' and set up the next call to be 'start + 1'
- return Generator(start, `generate_int_range`, [start+1, end]);
- } else {
- // We're done. Empty generator returned
- return Generator();
- }
- }
- // TODO Handle cases where there is no result, you simply want to call
- // a stateful function repeatedly
- // Initiate the generator
- var g = generate_int_range(1, 10000);
- // Loop through possible results
- while (g.has_value)
- {
- //print(g.value)
- g.next_value();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement