blob: 83ebe011035da9f37e1952895fb15b193dc071d1 [file] [log] [blame]
Guido van Rossumf4e13a42000-11-08 15:17:49 +00001# Coroutine example: controlling multiple instances of a single function
2
3from Coroutine import *
4
5# fringe visits a nested list in inorder, and detaches for each non-list
6# element; raises EarlyExit after the list is exhausted
7def fringe( co, list ):
8 for x in list:
9 if type(x) is type([]):
10 fringe(co, x)
11 else:
Guido van Rossumd42124c2001-03-22 13:36:39 +000012 co.back(x)
Guido van Rossumf4e13a42000-11-08 15:17:49 +000013
14def printinorder( list ):
15 co = Coroutine()
16 f = co.create(fringe, co, list)
17 try:
18 while 1:
19 print co.tran(f),
20 except EarlyExit:
21 pass
22 print
23
24printinorder([1,2,3]) # 1 2 3
25printinorder([[[[1,[2]]],3]]) # ditto
26x = [0, 1, [2, [3]], [4,5], [[[6]]] ]
27printinorder(x) # 0 1 2 3 4 5 6
28
29# fcmp lexicographically compares the fringes of two nested lists
30def fcmp( l1, l2 ):
31 co1 = Coroutine(); f1 = co1.create(fringe, co1, l1)
32 co2 = Coroutine(); f2 = co2.create(fringe, co2, l2)
33 while 1:
34 try:
35 v1 = co1.tran(f1)
36 except EarlyExit:
37 try:
38 v2 = co2.tran(f2)
39 except EarlyExit:
40 return 0
41 co2.kill()
42 return -1
43 try:
44 v2 = co2.tran(f2)
45 except EarlyExit:
46 co1.kill()
47 return 1
48 if v1 != v2:
49 co1.kill(); co2.kill()
50 return cmp(v1,v2)
51
52print fcmp(range(7), x) # 0; fringes are equal
53print fcmp(range(6), x) # -1; 1st list ends early
54print fcmp(x, range(6)) # 1; 2nd list ends early
55print fcmp(range(8), x) # 1; 2nd list ends early
56print fcmp(x, range(8)) # -1; 1st list ends early
57print fcmp([1,[[2],8]],
58 [[[1],2],8]) # 0
59print fcmp([1,[[3],8]],
60 [[[1],2],8]) # 1
61print fcmp([1,[[2],8]],
62 [[[1],2],9]) # -1
63
64# end of example