Think Functional

Simplify Your Code With Functional Programming

Motivation

Why you should keep you're eyes peeled over the next hour or so

it's fun

At least IMO

it's simple

immutability ftw

it's modern

perfect for parallel programming

Terminology

For the sole purpose of impressing your boss with your geeky hotness

functional programming

programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.

Mutability

characteristic of an Object that indicates the ability to change its state after creation.

first-class citizen

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.

copy / paste

A text editor function that is used by programmers that want to lose their jobs, or have swore revenge against their future selves.

Neckbeard

A phenomena that happens to programmers when learning functional languages (Haskell).

Common functions

Core functions used when doing functional programming

for each

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

map

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)

filter

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)

reduce

>>> 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)

collections

arr = [1, 2, 3, 4]

length = len(arr)
has_truth = any(arr)
is_truth = all(arr)

Common practices

For when you want to take your func-fu to the next level

currying

currying

>>> 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

Monads

Live coding session

Functionify an existing project

further reading

Think Functional

By mazyod

Think Functional

Simplify your code using functional programming

  • 691