Created
November 27, 2013 21:10
-
-
Save multidis/7683230 to your computer and use it in GitHub Desktop.
Functional programming tools in Python. Declarative programming style elements.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### List comprehension: map (+filter) part of map-reduce | |
## map: Mj <- Lj + 10 for all j | |
M = [x+10 for x in L] | |
## filter: select lines from file that start with 'p' and strip newlines | |
lines = [line.rstrip() for line in open('file.txt') if line[0]=='p'] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### State retention in functions: FP alternative to class attributes. | |
### NOTE: this is the idea of scala actor implementation. | |
### NOTE2: functools.partial provides an alternative. | |
## Closure (factory) function | |
def maker(N): | |
def action(X): | |
return X**N | |
return action | |
## N is being retained similarly to a class attribute | |
f = maker(2) | |
f(3) # 9 | |
g = maker(3) | |
g(3) # 27 | |
f(3) # still 9 | |
## with lambda | |
def func(): | |
x = 4 | |
action = (lambda n: x**n) ## x remembered from enclosing scope | |
return action | |
x = func() | |
x(2) # 4**2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment