Open frostburn opened 7 years ago
Some way of passing data back to the generator would also be nice.
Iterators with similiar API could be implemented without any modifications to the interpreter.
How would they work? Use an array as a stack or something?
This is how I implemented them:
{
"prototype": {
"constructor": (
"quote" swap !
),
"next": (
"state" swap has-own? ( "state" swap @ swap ) if
"quote" swap @ rot swap call
dup rot "state" swap ! swap
),
},
} "generator" const
Usage:
( 1 + ) generator new # Turn quote into generator.
0 swap # Sets initial value of generator to 0.
next println # Returns 1
next println # Returns 2
next println # Returns 3
If I understand correctly this only allows a single value to act as the state of the generator. It is also quite brittle if the quote happens to misuse the stack. Having a generator accidentally read or write onto your stack creates hard-to-debug issues. In my proposed implementation any misuse would raise a range error on the generator's local stack.
Make it possible to turn quotes into interruptible programs. Proposed example: