Simplify Your Code With Functional Programming
Why you should keep you're eyes peeled over the next hour or so
For the sole purpose of impressing your boss with your geeky hotness
a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.
A characteristic of an Object that indicates the ability to change its state after creation.
an entity which supports all the operations generally available to other entities. These operations typically include being passed as a parameter, returned from a function, and assigned to a variable.
A text editor function that is used by programmers that want to lose their jobs, or have swore revenge against their future selves.
A phenomena that happens to programmers when learning functional languages (Haskell).
Core functions used when doing functional programming
array = [1, 2, 3, 4]
for element in array:
print(element)
arr = [1, 2, 3, 4]
ind = 0
while ind < len(arr):
item = arr[ind]
print(item)
ind += 1
array = [1, 2, 3, 4]
result = map(str, array)
arr = [1, 2, 3, 4]
result = []
for item in arr:
str_object = str(item)
result.append(str_object)
array = [1, 2, 3, 4]
criteria = lambda item: item % 2 == 0
result = filter(criteria, array)
arr = [1, 2, 3, 4]
result = []
for item in arr:
if item % 2 == 0:
result.append(str_object)
>>> arr = [1, 2, 3, 4]
>>> average_calc = lambda prev, cur: prev + float(cur) / len(arr)
>>> result = reduce(average_calc, array, 0)
>>> result
2.5
arr = [1, 2, 3, 4]
result = 0
for item in arr:
result += item / len(arr)
arr = [1, 2, 3, 4]
length = len(arr)
has_truth = any(arr)
is_truth = all(arr)
For when you want to take your func-fu to the next level
>>> def test(one, two, three):
... print one, two, three
...
>>> curried = partial(test, 1)
>>> curried = partial(curried, 2)
>>> curried = partial(curried, 3)
>>> curried()
1 2 3
>>> def log(severity, message):
... print severity, message
...
>>> error = partial(log, "ERROR")
>>> warning = partial(log, "WARN")
>>> debug = partial(log, "DEBUG")
>>>
>>> debug("This is a debug message")
DEBUG This is a debug message
Functionify an existing project