8000 Adds compose docs · bitnom/functional-jargon-python@76668d9 · GitHub
[go: up one dir, main page]

Skip to content

Commit 76668d9

Browse files
authored
Adds compose docs
1 parent 03ec4b4 commit 76668d9

File tree

1 file changed

+34
-4
lines changed

1 file changed

+34
-4
lines changed

README.md

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ __Table of Contents__
1616
* [Closure (TODO)](#closure-todo)
1717
* [Partial Application](#partial-application)
1818
* [Currying](#currying)
19-
* [Function Composition (TODO)](#function-composition-todo)
19+
* [Function Composition](#function-composition)
2020
* [Continuation (TODO)](#continuation-todo)
2121
* [Side effects](#side-effects)
2222
* [Purity](#purity)
@@ -251,14 +251,44 @@ __Further reading__
251251
* [Hey Underscore, You're Doing It Wrong!](https://www.youtube.com/watch?v=m3svKOdZijA)
252252

253253

254-
## Function Composition (TODO)
254+
## Function Composition
255255

256-
The act of putting two functions together to form a third function where the output of one function is the input of the other.
256+
For example, you can compose `abs` and `int` functions like so:
257257

258258
```python
259-
# TODO
259+
>>> assert abs(int('-1')) == 1
260+
```
261+
262+
You can also create a third function
263+
that will have an input of the first one and an output of the second one:
264+
265+
```python
266+
>>> from typing import Callable, TypeVar
267+
268+
>>> _FirstType = TypeVar('_FirstType')
269+
>>> _SecondType = TypeVar('_SecondType')
270+
>>> _ThirdType = TypeVar('_ThirdType')
271+
272+
>>> def compose(
273+
... first: Callable[[_FirstType], _SecondType],
274+
... second: Callable[[_SecondType], _ThirdType],
275+
... ) -> Callable[[_FirstType], _ThirdType]:
276+
... return lambda argument: second(first(argument))
277+
278+
>>> assert compose(int, abs)('-1') == 1
260279
```
261280

281+
We already have this functions defined as `returns.functions.compose`!
282+
283+
```python
284+
>>> from returns.functions import compose
285+
>>> assert compose(bool, str)([]) == 'False'
286+
```
287+
288+
__Further reading__
289+
* [`compose` docs](https://returns.readthedocs.io/en/latest/pages/functions.html#compose)
290+
291+
262292
## Continuation (TODO)
263293

264294
At any given point in a program, the part of the code that's yet to be executed is known as a continuation.

0 commit comments

Comments
 (0)
0