Skip to content

Commit 933c676

Browse files
author
czheo
committed
2 parents 40f4d02 + dbc6f0d commit 933c676

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

README.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,4 +199,63 @@ list((stream() << [1, 1] << (lambda x, y: x + y)) /take/ 10)
199199
# If a function is met, stream will infinitely take the last N previous items as the input of the lambda to generate the next item.
200200
```
201201
-->
202+
203+
204+
### function composition
205+
206+
In math, `(f * g) (x) = f(g(x))`. This is called function composition.
207+
208+
``` python
209+
# this transfer a map object to list
210+
lmap = compose(list, map)
211+
# lmap equivalent to `list(map(...))`
212+
lmap(lambda x: x ** 2, range(10))
213+
```
214+
215+
Let's say we want to represent `f * g * h` in a program, i.e. `fn(x) = f(g(h(x)))`
216+
217+
``` python
218+
f = lambda x: x**2 + 1
219+
g = lambda x: 2*x - 1
220+
h = lambda x: -2 * x**3 + 3
221+
222+
fn = compose(f, g, h)
223+
224+
fn(5) # 245026
225+
```
226+
227+
or you can do
228+
229+
```python
230+
f = composable(lambda x: x**2 + 1)
231+
g = composable(lambda x: 2*x - 1)
232+
h = composable(lambda x: -2 * x**3 + 3)
233+
234+
fn = f * g * h
235+
236+
fn(5) # 245026
237+
```
238+
239+
Some times you may prefer the decorator way.
240+
241+
``` python
242+
# make your own composable functions
243+
@composable
244+
def add2(x):
245+
return x + 2
246+
247+
@composable
248+
def mul3(x):
249+
return x * 3
250+
251+
@composable
252+
def pow2(x):
253+
return x ** 2
254+
255+
fn = add2 * mul3 * pow2
256+
# equivalent to `add2(mul3(pow2(n)))`
257+
fn(5)
258+
# returns 5^2 * 3 + 2 = 77
259+
```
260+
202261
More receipes: https://github.com/czheo/syntax_sugar_python/tree/master/recipes

0 commit comments

Comments
 (0)