Functional Programming in Python

CIPPUS_Python   4th week

Yuanzheng Ci, Screw Studio @ DUT,

2017-11-26

Pure Functional Programming

  • Functions are first-class
  • Referential Transparency

Higher-order function

  • A function that takes a function as an argument value or
  • A function that returns a function as a return value

Closure

  • A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory

Closure

  • Python pre-computes which frame contains each name before executing the body of a function

Function Currying

  • Curry: Transform a multi-argument function into a single-argument, higher-order function
import functools

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

add(4, 2)
6

plus3 = functools.partial(add, 3)

plus3(4)
7

Decorators

  • @staticmethod
  • @classmethod
  • @lru_cache()
  • ...

Map Reduce

Iterator

from time import sleep


class CountDown:
    def __init__(self, step):
        self.step = step

    def __next__(self):
        """Return the next element."""
        if self.step <= 0:
            raise StopIteration
        self.step -= 1
        return self.step

    def __iter__(self):
        """Return the iterator itself."""
        return self


if __name__ == "__main__":
    print("Counting down:")

    for element in CountDown(10):
        print('*', element)
        sleep(0.2)
  • __next__  (next())
  • __iter__
  • Lazy Evaluation

yield and Generator

>>> def fibonacci():
...     a, b = 0, 1
...     while True:
...         yield b
...         a, b = b , a + b
...
>>> fib = fibonacci()
>>> fib
<generator object fibonacci at 0x7f6e8615b0f0>
>>> next(fib)
1
>>> next(fib)
1
>>> next(fib)
2
>>> next(fib)
3
>>> next(fib)
5
>>> next(fib)
8
>>> [next(fib) for _ in range(10)]
[13, 21, 34, 55, 89, 144, 233, 377, 610, 987]
def psychologist():
    print('Please tell me your problems')
    while True:
        answer = (yield)
        ....
psy = psychologist()
psy.send('wtf?')
>>> def AB():
...     yield 'A'
...     yield 'B'
...     yield from 'CD'
...
>>> ab = AB()
>>> ab
<generator object AB at 0x7f2ff66380a0>
>>> [x for x in ab]
['A', 'B', 'C', 'D']

eval and apply

eval and apply

with

with open(r'somefileName') as somefile:
    for line in somefile:
        print(line)
        # ...more code
somefile = open(r'somefileName')
try:
    for line in somefile:
        print(line)
        # ...more code
finally:
    somefile.close()

pass

def foo():
    pass

*args    **kwargs

def sum(*args):
    return reduce(add, args, 0)

sum(1, 2, 3)
sum(*[1, 2, 3])

def another_sum(sequence):
    return reduce(add, sequence, 0)

another_sum([1, 2, 3])

def wtf(**kwargs):
    pass

wtf(this=1)
wtf(my_money=1e10)

answer

Books for advanced level

Functional Programming in Python

By orashi

Functional Programming in Python

cippus fourth week python meetup

  • 182