-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathAsyncSugaredExamples.hx
520 lines (429 loc) · 12.9 KB
/
AsyncSugaredExamples.hx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
package;
import moon.core.Fiber;
import moon.core.Future;
import moon.core.Generator;
import moon.core.Observable;
import moon.core.Seq;
import moon.core.Signal;
// needed for custom wrappers using static extensions
using AsyncSugaredExamples;
// used by switch example below
enum Worker
{
Employee(name:String);
Manager(name:String, workers:Array<Worker>);
}
// used by custom wrapper example below
class CustomWrapper<T>
{
public var it:Iterable<T>;
public function new()
{
it = [];
}
/**
* You can define your own async type by having a static method
* named `fromAsync` with one argument of a valid async type.
*/
/*public static function fromAsync<A>(it:Iterable<A>):CustomWrapper<A>
{
trace("custom wrapper using static fromAsync method");
var obj = new CustomWrapper<A>();
obj.it = it;
return obj;
}*/
}
class AsyncTypeExtensions
{
/**
* Alternative method of creating wrappers:
* You can define your own async type by having a static method
* with one argument of a valid async type and a @asyncType meta.
*
* This method is used to create wrappers when you don't have access
* to the wrapping class. For example, 3rd party libraries.
*
* You need to include this class using static extensions (`using` keyword)
*/
@asyncType
public static function createCustomWrapper<A>(it:Iterable<A>):CustomWrapper<A>
{
trace("custom wrapper using static extensions");
var obj = new CustomWrapper<A>();
obj.it = it;
return obj;
}
}
/**
* Any function that contains @yield will be transformed into
* generator function, including nested functions and class methods.
*
* You can type the generator function with a valid async type, to
* get that type when the generator is called.
*
* Valid async generator types:
* Iterator<T>, Iterable<T>, Seq<T>, Generator<T,U>
*
* Valid async fiber types:
* Fiber<T>, Future<T>, Signal<T>, Observable<T>
*
* Async generator types are simply iterators. You need to manually
* iterate through them.
*
* Async fiber types are iterators added into a fiber object.
* The fiber `Processor` is usually added to your game loop or some
* interval/update function, and the processor will take turns
* switching between different fibers every loop.
*
* This allows you to have cooperative multitasking, something that
* wasn't available in some single threaded targets. Unlike threads,
* you don't need to worry about locking
*
* @author Munir Hussin
*/
//@:build(moon.core.Sugar.build()) // also works but has other stuff also
@:build(moon.core.Sugar.buildAsync())
class AsyncSugaredExamples
{
public static function main()
{
//methodExample();
//simpleExample();
//customWrapperExample();
awaitExample();
//tryExample();
//permutationsExample();
//nestedExample();
//fibonacciExample();
//sendExample();
//anotherSendExample();
//fiberExample();
//fiberFutureExample();
//fiberDurationExample();
}
public static function methodExample()
{
for (name in customIterator("Hello", "How are you?"))
{
trace(name);
}
}
public static function customIterator(greet:String, msg:String):Iterator<String>
{
var alice = Employee("alice");
var alice = Employee("alice"), bob = Employee("bob");
var carol = Employee("carol");
var dave = Manager("dave", [alice, bob, carol]);
for (p in [alice, bob, carol, dave])
{
//var x =
switch (p)
{
case Employee(name):
@yield (greet + " " + name + "! " + msg);
//Employee("aaa");
case Manager(name, workers):
@yield (greet + " manager " + name + "! How are " + workers.join(", ") + " doing?");
//Employee("bbb");
case _:
@yield "hello";
//Employee("ccc");
}
//@yield ("x is " + x);
trace("test");
}
}
public static function simpleExample()
{
function simple():Iterator<String>
{
@yield "foo";
@yield "bar";
@yield "baz";
}
trace("Generator Simple Example");
trace("");
trace("For loop to display yielded values");
var it = simple();
for (x in it)
{
trace(x);
}
trace("");
trace("Manually calling next()");
var it = simple();
try
{
trace(it.next());
trace(it.next());
trace(it.next());
trace(it.next()); // this raises exception
}
catch (ex:Dynamic)
{
trace("AsyncException: " + ex);
}
}
public static function customWrapperExample()
{
// experimental: define your own async type
function custom():CustomWrapper<String>
{
var a = [for (i in 0...5) i];
trace(a);
@yield "aaa";
@yield "bbb";
@yield "ccc";
}
trace("Custom Wrapper Example");
trace("");
var it = custom().it;
for (x in it)
{
trace(x);
}
}
public static function awaitExample()
{
var someFuture = new Future<Int>();
function await():Iterator<String>
{
@yield "foo";
var x:Int = @await someFuture;
trace('value of x is $x');
@yield "bar";
}
trace("Await Example");
trace("");
var it = await();
var i = 0;
while (it.hasNext())
{
// trigger completion when i is 3
if (i == 5) someFuture.complete(5318008);
trace(i + ": " + it.next());
++i;
}
}
public static function tryExample()
{
function trycatch():Iterator<String>
{
try
{
@yield "aaa";
@yield "bbb";
throw 123;
@yield "ccc";
}
catch (ex:Int)
{
@yield ("ddd " + ex);
}
catch (ex:Bool)
{
@yield ("eee " + ex);
}
}
trace("Try Example");
trace("");
var it = trycatch();
for (x in it)
{
trace(x);
}
}
public static function permutationsExample()
{
function permutations(items:Array<Dynamic>):Iterator<Array<Dynamic>>
{
var n = items.length;
if (n == 0)
@yield [];
else
for (i in 0...n)
for (cc in permutations(items.slice(0, i).concat(items.slice(i + 1))))
@yield [items[i]].concat(cc);
}
trace("Generator Permutations Example");
var it = permutations(["a", "b", "c"]);
for (x in it)
{
trace(x);
}
}
public static function nestedExample()
{
function range(start:Int, stop:Int, step:Int):Iterator<Int>
{
while (start < stop)
{
@yield start;
start += step;
}
}
trace("Generator Nested Example");
for (x in range(2, 6, 1))
{
for (y in range(4, 10, 2))
{
trace(x, y);
}
}
}
public static function fibonacciExample()
{
function fib():Iterator<Int>
{
var a = 0;
var b = 1;
while (true)
{
@yield a;
b = a + b;
@yield b;
a = a + b;
}
}
trace("Generator Fibonacci Example");
var it = fib();
for (i in 0...13)
{
trace(i + ": " + it.next());
}
}
public static function sendExample()
{
function sendFn(a:Int, b:String):Generator<Int, String>
{
trace("gen start");
for (vv in a...10)
{
if (vv == 5)
trace("yo" + @yield 999);
else
trace(b + @yield vv);
}
trace("gen end");
}
trace("Generator Send Example");
var it = sendFn(3, "hi");
var m = 10;
while (it.hasNext())
{
var out = it.send(" " + m++);
trace("out: " + out);
}
}
public static function anotherSendExample()
{
function makeObject():Generator<String, Float>
{
var z =
{
aaa: @yield "foo",
bbb: @yield "bar",
ccc: @yield "baz",
};
@yield ("Done: " + z);
}
trace("Generator Another Example");
var it = makeObject();
while (it.hasNext())
{
var out = it.send(Math.random());
trace("out: " + out);
}
}
public static function fiberExample()
{
function fiber(m:String, a:Int, b:Int):Fiber<Int>
{
trace(m + ": fiber start");
for (vv in a...b)
{
trace(m + ": " + vv);
@yield vv;
}
trace(m + ": fiber end");
}
trace("Fiber Example");
var f1 = fiber("foo", 1, 10);
var f2 = fiber("bar", 100, 120);
var f3 = fiber("baz", 1000, 1005);
var v4 = fiber("hey", 9995, 9999).sync();
trace("Immediate value: " + v4);
//f3.yielded.add(function(x:Int) trace("SIGNAL: " + x));
f1.result.log("Fiber 1: ");
f2.result.log("Fiber 2: ");
f3.result.log("Fiber 3: ");
// the cycle will go: foo bar bar baz foo bar bar baz ...
f2.priority = 2;
// this while loop represents your game update loop
while (Processor.main.hasNext())
{
// run the next 3 fibers
Processor.main.run(3);
}
}
public static function fiberFutureExample()
{
// Instead of returning a Fiber, you can also return a Future instead.
// The final value yielded will be the result of this future.
function fiberFuture(name:String, start:Int, stop:Int):Future<Int>
{
trace(name + ": fiber start");
for (i in start...stop)
{
trace(name + ": " + i);
@yield i;
}
trace(name + ": fiber end");
}
trace("Fiber Example");
var f1 = fiberFuture("foo", 1, 10);
var f2 = fiberFuture("bar", 100, 120);
var f3 = fiberFuture("baz", 1000, 1005);
//f3.yielded.add(function(x:Int) trace("SIGNAL: " + x));
f1.log("Fiber 1: ");
f2.log("Fiber 2: ");
f3.log("Fiber 3: ");
// this while loop represents your game update loop
while (Processor.main.hasNext())
{
// run the next 3 fibers
Processor.main.run(3);
}
}
public static function fiberDurationExample()
{
function fiberInfinite(name:String, start:Int):Fiber<Int>
{
trace(name + ": fiber start");
// infinite loop
while (true)
{
@yield start++;
}
// this will never reach
trace(name + ": fiber end");
}
trace("Fiber Duration Example");
var f1 = fiberInfinite("foo", 1);
var f2 = fiberInfinite("bar", 100);
var f3 = fiberInfinite("baz", 1000);
//f3.yielded.add(function(x:Int) trace("SIGNAL: " + x));
f1.result.log("Fiber 1: ");
f2.result.log("Fiber 2: ");
f3.result.log("Fiber 3: ");
f2.priority = 2;
// imagine this to be your update loop
for (i in 0...5)
{
trace("-----");
// run the fibers (so long as there's any) for 1.5 seconds
// with 10 fibers at a time
Processor.main.duration(1.5, 10);
}
}
}