coclass'coroutine'
NB. Coroutine is function that returns result ; function to return next result 
when called with ''
NB. J implementation is spectacularly easy to debug and use.
NB.CREATE:
NB. savedobject =. verb Coroutine [noun Initialdata]
NB.USE:
NB. resume__savedobject '' 
NB. after each call, the state is beheaded, or transform function passed as 
gerund is used.
Note 'Example'
   (a1=: {. Coroutine 1 2 3 4)  
+--+
|28|
+--+
   resume__a1 ''
1
   resume__a1 ''
2
   resume__a1 ''
3
   resume__a1 ''
4
   resume__a1 ''
   resume__a1 ''
)

function=: i.0
transform=: }.

create=: 3 : 0
  STATE=: y
)
destroy=: codestroy


resume=: 3 : 0
NB.if. 0=#STATE__m do. return. end.
NB.(STATE__m=: }.STATE__m) ] function__m STATE__m
if. 0=#STATE do. return. end.
(STATE=: transform STATE) ] function STATE
NB. possible alternative: call y function STATE to use param to resume.
NB. also possible to use gerund as function for STATE transform function 
instead of }.
)

lazy=: 3 : 0
NB. lazy data structures
NB. not meant to be used at same time/data as resume_coroutine_
NB. function is either a verb or gerund: 
NB. if verb, then new STATE=: f STATE, and return is f STATE
NB. if gerund then function is f-to-return`f-to-transform


)

cocurrent 'base'

Coroutine=: 2 : 0
lastobj =: n conew 'coroutine'
function__lastobj =: u
if. 4!:0 <'function__lastobj' do. else. NB. if gerund... if not, just behead 
list
     'function__lastobj transform__lastobj' =: function__lastobj end.
lastobj 
)

There is a bug in my gerund handling code, but it works if you accept the 
transform state verb to just be }. ... is there a way to convert a gerund into 
verbs instead of strings?

One use for this simple coroutine class is if you have a fairly complex 
processing of one tree or list, and you know the order of companion data you 
will need even if you might be skipping parts of it, or skipping through your 
processing tree.  Can also implement lazy evaluation through much the same way.



----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to