functional-python



functional-python

0 0


functional-python


On Github pori / functional-python

Functional Python

SRO Python Workshop #2

Created by Alexander Hernandez / @pori_alex

Join us at sropythonusers@umich.edu

How I use Functional Programming

Imperative Programming

Programming that changes state to complete a task.

    a = 0
    b = 0

    a += 160     # 160
    a /= 5       # 4

    def do_something(n):
        b = a + n

    do_something(10)

    print b     # 42

Functional Programming

Describing what a program is rather than how it works.

    a = 0
    b = a + 160     # 160
    c = b / 5        # 4

    def do_something(a, b):
        return a + b

    d = do_something(c, 10)

    print d     # 42

FP Characteristics

  • Recursion
  • Purity
    • Immutable
    • Lazy
    • Lack of Side Effects
  • High Order Functions
    • First Class Citizens

Lambdas

A shorthand for functions.

# lambda x, y, ...: expression
sgn = lambda x: -1 if (x < 0) else 1 if (x > 0) else 0

sgn(-5) # -1
sgn(5)  # 1
sgn(0)  # 0

High Order Functions

Functions that take other functions as arguments, return functions, or both.

The most famous ones are map(), reduce(), filter().

High Order Function Examples

list = [1, 2, 3, 4, 5]

def square(x):
    return x*x

squared = map(square, list)      # [1, 4, 9, 16, 25]
gt5 = filter(lambda x: x > 5, squared)   # [9, 16, 25]
sum = reduce(lambda x, y: x + 7, gt5)    # 23

Pure Functions

Functions that take input and produce an output. The same input will always produce the same output, lacking side effects.

square = lambda x: x**2

As opposed to:

power = 2

square = lambda x: x**power

print square(2) # 4

power = 0

print square(2) # 1

Declarative Syntax

Syntax that sounds like what it's doing.

i.e.

SELECT * FROM superheroes WHERE city LIKE 'Metropolis';

In Python, this could be:

select('superheroes', where({ 'city': 'Metropolis' }))

An Example using Fibonacci

Here's a mathematical definition:

An Example using Fibonacci

An imperative implementation:

def fib(n):
 a, b = 0, 1

 for i in range(0, n):
  a, b = b, a + b

 return a

Now let's try this Functionally:

def fib(n):
 if n == 0: return 0
 elif n == 1: return 1
 else: return fib(n - 1) + fib(n - 2)

Read CSV Example

An imperative implementation:

import csv

def csvtodict (csvFile, delim):
 headers = None
 content = {}
 reader = csv.reader(open(csvFile), delimiter=delim)
 i = 1

 for row in reader:
  if reader.line_num == 1:
     headers = row[0:]
  else:
     content[i] = dict(zip(headers, row[0:]))

    i = i + 1

 return content

incsv = r"path\to\file"

d_csv = csvtodict(incsv, ',')
print len(d_csv)

Read CSV Example

A functional implementation:

import csv

load_csv = lambda f, delim: csv.reader(open(f), delimiter=delim)

def csvtodict (csvFile, delim):
 reader = load_csv(csvFile, delim)
 headers = headers.next()
 content = map(lambda row: zip(headers, row), reader)

 return content

incsv = r"path\to\file"
csv_default_delim = lambda f: csvdict(f, ',')
d_csv = csv_default_delim(incsv)

print len(d_csv)

FP Caveats in Python

  • No pattern matching
  • No tail recursion
  • No automatic currying
  • No laziness
  • Limited expression syntax

FP Resources

Thanks!

Any questions?

Don't forget to join us at sropythonusers@umich.edu

References

Functional Python SRO Python Workshop #2 Created by Alexander Hernandez / @pori_alex Join us at sropythonusers@umich.edu