t207.py

00001 # This file is Copyright 2003, 2006, 2007, 2009 Dean Hall.
00002 #
00003 # This file is part of the Python-on-a-Chip program.
00004 # Python-on-a-Chip is free software: you can redistribute it and/or modify
00005 # it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1.
00006 #
00007 # Python-on-a-Chip is distributed in the hope that it will be useful,
00008 # but WITHOUT ANY WARRANTY; without even the implied warranty of
00009 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00010 # A copy of the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1
00011 # is seen in the file COPYING up one directory from this.
00012 
00013 #
00014 # System Test 207
00015 # Add support for the yield keyword
00016 #
00017 # To learn about generators: http://www.dabeaz.com/generators/Generators.pdf
00018 #
00019 
00020 
00021 # Generator-expressions
00022 
00023 a = [1,2,3,4]
00024 b = (2*x for x in a)
00025 c = [2*x for x in a]
00026 n = 0
00027 for i in b:
00028     print i,
00029     assert i == c[n]
00030     n += 1
00031 print
00032 
00033 
00034 # Generator-iterators
00035 
00036 def fib():
00037     a, b = 0, 1
00038     while True:
00039         yield a
00040         a, b = b, a+b
00041 
00042 print "Fibonacci generator:",
00043 for i in fib():
00044     print i,
00045     if i > 256:
00046         break
00047 print
00048 
00049 f = fib()
00050 assert type(f) == 0x09
00051 assert f.next() == 0
00052 assert f.next() == 1
00053 assert f.next() == 1
00054 assert f.next() == 2
00055 assert f.next() == 3
00056 assert f.next() == 5
00057 assert f.next() == 8
00058 
00059 
00060 # Generator-coroutines
00061 
00062 def show(n):
00063     i = 0
00064     while True:
00065         msg = (yield i)
00066         print "I'm going to say this", n, "times:", msg * n
00067         i += 1
00068 
00069 s3 = show(3)
00070 s4 = show(4)
00071 assert s3.next() == 0
00072 assert s4.next() == 0
00073 assert s3.send("moo") == 1
00074 assert s4.send("baa") == 1
00075 assert s3.send("cow") == 2
00076 assert s4.send("dog") == 2

Generated on Mon Oct 18 07:40:47 2010 for Python-on-a-chip by  doxygen 1.5.9