第11章 函数和函数式编程(6)

11.9 递归

如果一个新的调用能在相同过程中较早的调用结束之前开始,那么该过程就是递归。

>>> def factorial(num):
... if num == 1:
... return num
... else:
... return num * factorial(num-1)
...
>>> factorial(20)
2432902008176640000L
>>> factorial(4)
24
>>>

11.10 生成器

什么是Python式的生成器?从语法上讲,生成器是一个带yield语句的函数。一个函数或者子程序只返回一次,但一个生成器能暂停执行并返回一个中间的结果——那就是yield语句的功能,返回一个值给调用者并暂停执行。当生成器的next()方法被调用的时候,它会准确地从离开地方继续。

>>> def simple_gen():
... yield 1
... yield 'haha'
...
>>> for i in simple_gen():
... print i
...
1
haha
>>>

11.10.2 加强的生成器特性

在Python2.5中, 一些新特性加入到生成器中,所以除了next()来获得下个生成的值,用户可以将值回送给生成器[send()],在生成器中抛出异常,以及要求生成器推出[close()]。

>>> def counter(start_at = 0):
... count = start_at
... while True:
... val = (yield count)
... if val is not None:
... count = val
... else:
... count += 1
...
>>> count = counter()
>>> count.next()
0
>>> count.next()
1
>>> count.send(100)
100
>>> count.next()
101
>>> count.close()
>>> count.next()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
StopIteration
>>>

你可能感兴趣的:(函数式编程)