- Functional Python Programming
- Steven F. Lott
- 237字
- 2021-08-27 19:20:25
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.
- Instant Node Package Manager
- 程序員面試白皮書
- 構(gòu)建移動(dòng)網(wǎng)站與APP:HTML 5移動(dòng)開發(fā)入門與實(shí)戰(zhàn)(跨平臺(tái)移動(dòng)開發(fā)叢書)
- 樂學(xué)Web編程:網(wǎng)站制作不神秘
- 薛定宇教授大講堂(卷Ⅳ):MATLAB最優(yōu)化計(jì)算
- Backbone.js Blueprints
- ASP.NET Core 2 Fundamentals
- 好好學(xué)Java:從零基礎(chǔ)到項(xiàng)目實(shí)戰(zhàn)
- 編程可以很簡單
- Python網(wǎng)絡(luò)爬蟲技術(shù)與應(yīng)用
- TypeScript 2.x By Example
- Clojure High Performance Programming(Second Edition)
- 寫給青少年的人工智能(Python版·微課視頻版)
- R語言實(shí)戰(zhàn)(第2版)
- 安卓工程師教你玩轉(zhuǎn)Android