Skip to content

Instantly share code, notes, and snippets.

@lefticus
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lefticus/0358b6450cc994c71c70 to your computer and use it in GitHub Desktop.
Save lefticus/0358b6450cc994c71c70 to your computer and use it in GitHub Desktop.
chaiscript generator proposal
// 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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment