Functional programming in Python 1st Edition David Mertzinstant download
Functional programming in Python 1st Edition David Mertzinstant download
https://ebookultra.com/download/functional-programming-in-
python-1st-edition-david-mertz/
https://ebookultra.com/download/text-processing-in-python-2-print-
edition-mertz/
https://ebookultra.com/download/functional-programming-in-c-first-
edition-ivan-cukic/
https://ebookultra.com/download/maya-programming-with-python-
cookbook-1st-edition-herbez/
https://ebookultra.com/download/parallel-programming-with-python-
first-edition-jan-palach/
Real World Functional Programming With Examples in F and C
1st Edition Tomas Petricek
https://ebookultra.com/download/real-world-functional-programming-
with-examples-in-f-and-c-1st-edition-tomas-petricek/
https://ebookultra.com/download/principles-of-soft-computing-using-
python-programming-1st-edition-gypsy-nandi/
https://ebookultra.com/download/python-cookbook-3rd-edition-david-
beazley/
https://ebookultra.com/download/introduction-to-computing-and-
programming-in-python-a-multimedia-approach-mark-j-guzdial/
https://ebookultra.com/download/elements-of-programming-interviews-in-
python-1st-edition-adnan-aziz-amit-prakash-tsung-hsien-lee/
Functional programming in Python 1st Edition David
Mertz Digital Instant Download
Author(s): David Mertz
ISBN(s): 9781491928561, 1491928565
Edition: 1
File Details: PDF, 1.56 MB
Year: 2015
Language: english
Functional
Programming
in Python
David Mertz
Additional
Resources
4 Easy Ways to Learn More and Stay Current
Programming Newsletter
Get programming r elated news and content delivered weekly to your inbox.
oreilly.com/programming/newsletter
O’Reilly Radar
Read more insight and analysis about emerging technologies.
radar.oreilly.com
Conferences
Immerse yourself in learning at an upcoming O’Reilly conference.
conferences.oreilly.com
©2015 O’Reilly Media, Inc. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. #15305
Functional Programming
in Python
David Mertz
Functional Programming in Python
by David Mertz
Copyright © 2015 O’Reilly Media, Inc. All rights reserved.
Attribution-ShareAlike 4.0 International (CC BY-SA 4.0).
See: http://creativecommons.org/licenses/by-sa/4.0/
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA
95472.
O’Reilly books may be purchased for educational, business, or sales promotional use.
Online editions are also available for most titles (http://safaribooksonline.com). For
more information, contact our corporate/institutional sales department:
800-998-9938 or [email protected].
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Functional Pro‐
gramming in Python, the cover image, and related trade dress are trademarks of
O’Reilly Media, Inc.
While the publisher and the author have used good faith efforts to ensure that the
information and instructions contained in this work are accurate, the publisher and
the author disclaim all responsibility for errors or omissions, including without limi‐
tation responsibility for damages resulting from the use of or reliance on this work.
Use of the information and instructions contained in this work is at your own risk. If
any code samples or other technology this work contains or describes is subject to
open source licenses or the intellectual property rights of others, it is your responsi‐
bility to ensure that your use thereof complies with such licenses and/or rights.
978-1-491-92856-1
[LSI]
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v
Callables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Named Functions and Lambdas 12
Closures and Callable Instances 13
Methods of Classes 15
Multiple Dispatch 19
Lazy Evaluation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
The Iterator Protocol 27
Module: itertools 29
Higher-Order Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Utility Higher-Order Functions 35
The operator Module 36
The functools Module 36
Decorators 37
iii
Preface
• Functions are first class (objects). That is, everything you can do
with “data” can be done with functions themselves (such as
passing a function to another function).
• Recursion is used as a primary control structure. In some lan‐
guages, no other “loop” construct exists.
v
• There is a focus on list processing (for example, it is the source
of the name Lisp). Lists are often used with recursion on sublists
as a substitute for loops.
• “Pure” functional languages eschew side effects. This excludes
the almost ubiquitous pattern in imperative languages of assign‐
ing first one, then another value to the same variable to track
the program state.
• Functional programming either discourages or outright disal‐
lows statements, and instead works with the evaluation of
expressions (in other words, functions plus arguments). In the
pure case, one program is one expression (plus supporting defi‐
nitions).
• Functional programming worries about what is to be computed
rather than how it is to be computed.
• Much functional programming utilizes “higher order” functions
(in other words, functions that operate on functions that oper‐
ate on functions).
vi | Preface
functional programming are available. The one exception here is
that I will discuss Matthew Rocklin’s multipledispatch as the best
current implementation of the concept it implements.
Most third-party libraries around functional programming are col‐
lections of higher-order functions, and sometimes enhancements to
the tools for working lazily with iterators contained in itertools.
Some notable examples include the following, but this list should
not be taken as exhaustive:
Resources
There are a large number of other papers, articles, and books written
about functional programming, in Python and otherwise. The
Python standard documentation itself contains an excellent intro‐
duction called “Functional Programming HOWTO,” by Andrew
Kuchling, that discusses some of the motivation for functional pro‐
gramming styles, as well as particular capabilities in Python.
Preface | vii
Mentioned in Kuchling’s introduction are several very old public
domain articles this author wrote in the 2000s, on which portions of
this report are based. These include:
A Stylistic Note
As in most programming texts, a fixed font will be used both for
inline and block samples of code, including simple command or
function names. Within code blocks, a notional segment of pseudo-
code is indicated with a word surrounded by angle brackets (i.e., not
valid Python), such as <code-block>. In other cases, syntactically
valid but undefined functions are used with descriptive names, such
as get_the_data().
viii | Preface
(Avoiding) Flow Control
Encapsulation
One obvious way of focusing more on “what” than “how” is simply
to refactor code, and to put the data construction in a more isolated
place—i.e., in a function or method. For example, consider an exist‐
ing snippet of imperative code that looks like this:
1
# configure the data to start with
collection = get_initial_state()
state_var = None
for datum in data_set:
if condition(state_var):
state_var = calculate_from(datum)
new = modify(datum, state_var)
collection.add_to(new)
else:
new = modify_differently(datum)
collection.add_to(new)
Comprehensions
Using comprehensions is often a way both to make code more com‐
pact and to shift our focus from the “how” to the “what.” A compre‐
hension is an expression that uses the same keywords as loop and
conditional blocks, but inverts their order to focus on the data
Generators
Generator comprehensions have the same syntax as list comprehen‐
sions—other than that there are no square brackets around them
(but parentheses are needed syntactically in some contexts, in place
of brackets)—but they are also lazy. That is to say that they are
merely a description of “how to get the data” that is not realized
until one explicitly asks for it, either by calling .next() on the
object, or by looping over it. This often saves memory for large
sequences and defers computation until it is actually needed. For
example:
log_lines = (line for line in read_line(huge_log_file)
if complex_condition(line))
Comprehensions | 3
For typical uses, the behavior is the same as if you had constructed a
list, but runtime behavior is nicer. Obviously, this generator compre‐
hension also has imperative versions, for example:
def get_log_lines(log_file):
line = read_line(log_file)
while True:
try:
if complex_condition(line):
yield line
line = read_line(log_file)
except StopIteration:
raise
log_lines = get_log_lines(huge_log_file)
Yes, the imperative version could be simplified too, but the version
shown is meant to illustrate the behind-the-scenes “how” of a for
loop over an iteratable—more details we also want to abstract from
in our thinking. In fact, even using yield is somewhat of an abstrac‐
tion from the underlying “iterator protocol.” We could do this with a
class that had .__next__() and .__iter__() methods. For example:
class GetLogLines(object):
def __init__(self, log_file):
self.log_file = log_file
self.line = None
def __iter__(self):
return self
def __next__(self):
if self.line is None:
self.line = read_line(log_file)
while not complex_condition(self.line):
self.line = read_line(self.log_file)
return self.line
log_lines = GetLogLines(huge_log_file)
Aside from the digression into the iterator protocol and laziness
more generally, the reader should see that the comprehension focu‐
ses attention much better on the “what,” whereas the imperative ver‐
sion—although successful as refactorings perhaps—retains the focus
on the “how.”
Recursion
Functional programmers often put weight in expressing flow con‐
trol through recursion rather than through loops. Done this way, we
can avoid altering the state of any variables or data structures within
an algorithm, and more importantly get more at the “what” than the
“how” of a computation. However, in considering using recursive
styles we should distinguish between the cases where recursion is
just “iteration by another name” and those where a problem can
readily be partitioned into smaller problems, each approached in a
similar way.
There are two reasons why we should make the distinction men‐
tioned. On the one hand, using recursion effectively as a way of
marching through a sequence of elements is, while possible, really
not “Pythonic.” It matches the style of other languages like Lisp, def‐
initely, but it often feels contrived in Python. On the other hand,
Python is simply comparatively slow at recursion, and has a limited
stack depth limit. Yes, you can change this with sys.setrecursion
limit() to more than the default 1000; but if you find yourself
doing so it is probably a mistake. Python lacks an internal feature
called tail call elimination that makes deep recursion computation‐
ally efficient in some languages. Let us find a trivial example where
recursion is really just a kind of iteration:
def running_sum(numbers, start=0):
if len(numbers) == 0:
print()
return
total = numbers[0] + start
print(total, end=" ")
running_sum(numbers[1:], total)
Recursion | 5
Exploring the Variety of Random
Documents with Different Content
ajattelin, että sinä itse olisit toisten nuorten mukana ja ehkä ottaisit
osaa kilpailuihin, Mercy."
"Minä, isä?"
"Ne sanovat, ettet sinä enää ole sama iloinen, pikku tyttönen kuin
ennen", hän sanoi.
"Ainoastaan mitä?"
Kun Bonnithorne jätti hiilenpolttajan, hän kulki sitä tietä, joka vei
Newlannin joen yli ja kääntyi Ankerias-kallioille päin. Siten hän joutui
ihan lähelle urheilijoita. Hän sattui juuri kuulemaan laakson väen
naurun, kun kerjäläinen kertoi, että hän oli nähnyt Paul Ritsonin
Hendonissa. Hetkistä myöhemmin hän kohtasi Hugh Ritsonin tiellä.
Tervehdys oli lyhyt ja kursailematon, kun nämä kaksi toisensa
tapasivat.
"Niinpä niin, pidä sinä varasi! Miksi sinä oletkin kahdella päällä?
Sinuun sopii hyvin sananlasku kissasta ja kalasta."
"Miksi sinä sitten ehdotit sitä? Oliko se ajatus minun vai sinun?
Minä tahdoin pelastaa tytön häpeästä. Täällä hänellä on
pataljoonittain häpäisijöitä. Lähetä tyttö pois, niin sinä riistät heiltä
hyvän juorun aiheen."
Hugh Ritsonin otsa rypistyi ja hän sanoi: "Jos minä olen yhden
tyhmän työn kautta ajanut elämäni karille, eipä sillä väliä. En ole
korkealta kaatunut. Minä olen onnettomuuteen tuomittu mies."
"Anteeks', herraseni! Minä luulin, että sinä vielä olit kovin nuori",
sanoi herra Bonnithorne.
"Entäs sitten?"
"Eivätkö asiasi olisi niin pahasti, jos sinä et olisi toinen poika."
"Et koskaan."
"Äpäräpoika?"
"Ormerod."
"Grace."
"Paul."
Nimi meni kuin nuoli hänen lävitsensä. Sitten hän sanoi melkein
masentuneena:
*****
Varjot laaksossa olivat pidentyneet. Purppurainen rusko leikitteli
kaukaisilla huipuilla, ja synkkä, tumma sini asettui räystäitten alle.
Yksinäinen varis lennähteli hämärtyvässä illassa päästellen silloin
tällöin ilmoille yksitoikkoisen sävelensä. Illan yhä hämärtyessä saapui
kaksi vanhanpuoleista henkilöä pihaan.
IV LUKU.
"Tule, elä vaivoo ihtees ennee sillä! Kun min' oon tehnyt
testamenttin' ja asettanut Paulin samanarvoiseksi toisen poijan
kanssa, ei kukkaan voi juoruta mittään kun vain emme ite kerro."
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookultra.com