Skip to content

Instantly share code, notes, and snippets.

@multidis
Created November 27, 2013 21:10
Show Gist options
  • Save multidis/7683230 to your computer and use it in GitHub Desktop.
Save multidis/7683230 to your computer and use it in GitHub Desktop.
Functional programming tools in Python. Declarative programming style elements.
### 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']
### 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