blob: bc2e3ed42af6d7d15e88522424c564c69d3d4c5d [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
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007def fringe(co, list):
Guido van Rossumf4e13a42000-11-08 15:17:49 +00008 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
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000014def printinorder(list):
Guido van Rossumf4e13a42000-11-08 15:17:49 +000015 co = Coroutine()
16 f = co.create(fringe, co, list)
17 try:
18 while 1:
Collin Winter6f2df4d2007-07-17 20:59:35 +000019 print(co.tran(f), end=' ')
Guido van Rossumf4e13a42000-11-08 15:17:49 +000020 except EarlyExit:
21 pass
Collin Winter6f2df4d2007-07-17 20:59:35 +000022 print()
Guido van Rossumf4e13a42000-11-08 15:17:49 +000023
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
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000030def fcmp(l1, l2):
Guido van Rossumf4e13a42000-11-08 15:17:49 +000031 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
Collin Winter6f2df4d2007-07-17 20:59:35 +000052print(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
Guido van Rossumf4e13a42000-11-08 15:17:49 +000063
64# end of example