File: generator.vala

package info (click to toggle)
vala 0.56.18-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 57,468 kB
  • sloc: ansic: 581,293; sh: 5,334; makefile: 3,946; xml: 3,161; yacc: 1,219; lex: 374; javascript: 23
file content (60 lines) | stat: -rw-r--r-- 1,051 bytes parent folder | download | duplicates (4)
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
// This is based on Luca Bruno's Generator. It illustrates using async methods
// to emulate a generator style of iterator coding. Note that this runs fine
// without a main loop.

abstract class Generator<G> {
	bool consumed;
	unowned G value;
	SourceFunc callback;

	protected Generator () {
		helper.begin ();
	}

	async void helper () {
		yield generate ();
		consumed = true;
	}

	protected abstract async void generate ();

	protected async void feed (G value) {
		this.value = value;
		this.callback = feed.callback;
		yield;
	}

	public bool next () {
		return !consumed;
	}

	public G get () {
		var result = value;
		callback ();
		return result;
	}

	public Generator<G> iterator () {
		return this;
	}
}

class IntGenerator : Generator<int> {
	protected override async void generate () {
		for (int i = 0; i < 10; i++) {
			 if (i % 2 == 0)
			 	yield feed (i);
		}
	}
}

void main () {
	var gen = new IntGenerator ();
	string result = "";

	foreach (var item in gen)
		result += "%i ".printf (item);

	assert (result == "0 2 4 6 8 ");
}