官术网_书友最值得收藏!

Combining generator expressions

The essence of functional programming comes from the ways we can easily combine generator expressions and generator functions to create very sophisticated composite processing sequences. When working with generator expressions, we can combine generators in several ways.

One common way to combine generator functions is when we create a composite function. We may have a generator that computes (f(x) for x in range()). If we want to compute g(f(x)), we have several ways to combine two generators.

We can tweak the original generator expression as follows:

g_f_x = (g(f(x)) for x in range())  

While technically correct, this defeats any idea of reuse. Rather than reusing an expression, we rewrote it.

We can also substitute one expression within another expression, as follows:

g_f_x = (g(y) for y in (f(x) for x in range()))

This has the advantage of allowing us to use simple substitution. We can revise this slightly to emphasize reuse, using the following commands:

f_x = (f(x) for x in range())
g_f_x = (g(y) for y in f_x)  

This has the advantage of leaving the initial expression, (f(x) for x in range()), essentially untouched. All we did was assign the expression to a variable.

The resulting composite function is also a generator expression, which is also lazy. This means that extracting the next value from g_f_x will extract one value from f_x, which will extract one value from the source range() function.

主站蜘蛛池模板: 明水县| 玉林市| 灵石县| 龙陵县| 唐山市| 高雄县| 沧源| 元谋县| 开远市| 四川省| 昌邑市| 福贡县| 延长县| 周口市| 绥化市| 邯郸市| 黄龙县| 铁岭市| 略阳县| 东港市| 黔西县| 延庆县| 广饶县| 南江县| 嘉义市| 迁西县| 永胜县| 临江市| 邵阳县| 淳化县| 旅游| 宝山区| 通辽市| 弋阳县| 涟源市| 黔西县| 宁南县| 眉山市| 仁怀市| 商丘市| 蒙阴县|