Skip to content

Improving example codes. #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions docs/decoupled.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,12 +176,28 @@ def reversi(arr):
def reversi(arr):
"""Reverses a list."""
reved = []
for i in range(len(arr)):
reved.append(arr[len(arr) - 1 - i])
for i in reversed(range(len(arr))):
reved.append(arr[i])
return reved
```
````

````{tabbed} Even better code using list indexing
```
def reversi(arr):
"""Reverses a list."""
return arr[::-1]
```
````

````{tabbed} Even better code version using built-in functions
```
def reversi(arr):
"""Reverses a list."""
return list(reversed(arr))
```
````

Functions with side effects can be hard to reason about: you often need to understand their internals and state in order to use them properly. They're also harder to test. **Not every function with side effects is problematic, however**. My pragmatic advice is to first learn to spot and understand pure functions. Then organize your code so that many functions are pure, and those that are not are well-behaved.

```{figure} figures/pure-impure.svg
Expand Down