Python FP (Slides) (2018 Loidll)
Python FP (Slides) (2018 Loidll)
Computations in functional languages are free of side effects. There is a focus on list processing. Lists are often used with
See above: these languages are referentially transparent. recursion on sublists as a substitute for loops.
Computations in functional languages are state-less. This Functional programming either discourages or outright disallows
excludes the almost ubiquitous pattern in imperative languages of statements, and instead works with the evaluation of expressions
assigning first one, then another value to the same variable to (in other words, functions plus arguments). In the pure case, one
track the program state. program is one expression (plus supporting definitions).
Functions are first class (objects). Everything you can do with Functional programming focusses on what is to be computed
“data” can be done with functions themselves (such as passing a rather than how it is to be computed.
function to another function). Much functional programming utilises “higher order” functions (in
Recursion is used as a primary control structure. In some other words, functions that operate on functions that operate on
languages, no other “loop” construct exists. functions).
Hans-Wolfgang Loidl (Heriot-Watt Univ) Python Functional F20SC/F21SC — 2018/19 3 / 27 Hans-Wolfgang Loidl (Heriot-Watt Univ) Python Functional F20SC/F21SC — 2018/19 4 / 27
Functional languages are free of state Functional languages are free of state (cont’d)
Example Example
def square(x): def square(x):
return x*x return x*x
These change the way how you think about the data-structure: focus
on what the collection is, rather than how it is constructed.
Example
1 List comprehensions
combs = [(x, y) for x in [1,2,3] for y in [1,2,3] if x != y]
2 Set and dictionary comprehensions
3 Libraries of higher-order functions (map, reduce, zip) This is equivalent to this more verbose code
4 Iterators (also called “lazy data structures”) Example
Material from Functional Programming in Python, by David Mertz, combs = []
O’Reilly Media, 2015. for x in [1,2,3]:
for y in [1,2,3]:
if x != y:
combs.append((x, y))
Hans-Wolfgang Loidl (Heriot-Watt Univ) Python Functional F20SC/F21SC — 2018/19 7 / 27 Hans-Wolfgang Loidl (Heriot-Watt Univ) Python Functional F20SC/F21SC — 2018/19 8 / 27
Generator comprehensions Generator comprehensions (cont’d)
These describe “how to get the data”, that is not realised until one A traditional, more verbose, version:
explicitly asks for it. They implement lazy data structures.
Example
Example def proc_file(file):
with open(file,"r") as f: """Find read events in an issuu log file."""
xs = (line for line in f f = open(file,"r")
if re.search(’"event_type":"read"’, line)) for line in f:
if re.search(’"event_type":"read"’, line):
yield line
NB: in this example, f is a generator, iterating over the file; you can’t f.close()
directly ask for its length
2
See this sample source code
Hans-Wolfgang Loidl (Heriot-Watt Univ) Python Functional F20SC/F21SC — 2018/19 9 / 27 Hans-Wolfgang Loidl (Heriot-Watt Univ) Python Functional F20SC/F21SC — 2018/19 10 / 27
Hans-Wolfgang Loidl (Heriot-Watt Univ) Python Functional F20SC/F21SC — 2018/19 15 / 27 Hans-Wolfgang Loidl (Heriot-Watt Univ) Python Functional F20SC/F21SC — 2018/19 16 / 27
Recursion vs. Iteration The concept of “lazy data structures”
Hans-Wolfgang Loidl (Heriot-Watt Univ) Python Functional F20SC/F21SC — 2018/19 19 / 27 Hans-Wolfgang Loidl (Heriot-Watt Univ) Python Functional F20SC/F21SC — 2018/19 20 / 27
Case Study: Higher-order Functions in Python A simple example of using higher-order functions
Example
Python supports higher-order functions def my_cmp(x,y):
"""Custom comparison operator to return inverse of the defaul
This means, functions can be assigned to variables return (-1)*(x-y);
The variable can then be called like a function ...
xs = mkList(n)
See the simple histo.py sample sources from the libraries
...
slides. ys = list(xs) # this clones the input
Functions can also be passed to other functions to modify the ys.sort() # this sorts the list
behaviour zs = list(xs)
zs.sort(key=functools.cmp_to_key(my_cmp)) # comp. function
One concrete application of this is modifying how sorting works
...
The sample code is in ho sort.py. zs = list(xs)
zs.sort(key=functools.cmp_to_key(gcd_cmp)) # comp. function
3
In Python 2 use: zs.sort(cmp=my cmp)
Hans-Wolfgang Loidl (Heriot-Watt Univ) Python Functional F20SC/F21SC — 2018/19 21 / 27 Hans-Wolfgang Loidl (Heriot-Watt Univ) Python Functional F20SC/F21SC — 2018/19 22 / 27
Towards the CW
Documents Readers
Input
Hans-Wolfgang Loidl (Heriot-Watt Univ) Python Functional F20SC/F21SC — 2018/19 23 / 27 Hans-Wolfgang Loidl (Heriot-Watt Univ) Python Functional F20SC/F21SC — 2018/19 24 / 27
Towards the CW Simple solution to “favourite number”
Example
def mostFavNum(dict):
"""Return the most favourite number."""
In our favourite number example # we use sets to collect the numbers
xs = set([])
we have numbers instead of documents (as circles)
# iterate over the dictionary entries
we have names instead of readers (as boxes) for k in dict.keys():
the structure of the computation we need to do is similar to the xs = xs | set(dict[k])
coursework # decorate each number with the matches, and use this as 1st
xs_dec = [ (countMatches(x,dict), x) for x in xs ]
# sort the list by first component in the tuple (no of matche
xs_dec.sort()
# return xs_dec[-10:-1] # return largest 10 values, if you p
n, x = xs_dec[-1] # largest elem
return x # return it’s value
Hans-Wolfgang Loidl (Heriot-Watt Univ) Python Functional F20SC/F21SC — 2018/19 25 / 27 Hans-Wolfgang Loidl (Heriot-Watt Univ) Python Functional F20SC/F21SC — 2018/19 26 / 27
Higher-order version