-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctional-programming.html
More file actions
626 lines (557 loc) · 68.1 KB
/
functional-programming.html
File metadata and controls
626 lines (557 loc) · 68.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
<!DOCTYPE html>
<html lang="en" xml:lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Chapter 8 Functional Programming | Introduction to Programming</title>
<meta name="description" content="Course reader for IMT/LIS 511: Introduction to Programming for Information and Data Science." />
<meta name="generator" content="bookdown 0.24 and GitBook 2.6.7" />
<meta property="og:title" content="Chapter 8 Functional Programming | Introduction to Programming" />
<meta property="og:type" content="book" />
<meta property="og:url" content="https://infx511.github.io/" />
<meta property="og:description" content="Course reader for IMT/LIS 511: Introduction to Programming for Information and Data Science." />
<meta name="github-repo" content="infx511/book" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="Chapter 8 Functional Programming | Introduction to Programming" />
<meta name="twitter:description" content="Course reader for IMT/LIS 511: Introduction to Programming for Information and Data Science." />
<meta name="author" content="Joel Ross" />
<meta name="date" content="2023-07-26" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="shortcut icon" href="img/ischool-gold.png" type="image/x-icon" />
<link rel="prev" href="searching.html"/>
<link rel="next" href="pandas.html"/>
<script src="libs/header-attrs-2.11/header-attrs.js"></script>
<script src="libs/jquery-3.6.0/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/fuse.js@6.4.6/dist/fuse.min.js"></script>
<link href="libs/gitbook-2.6.7/css/style.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-table.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-bookdown.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-highlight.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-search.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-fontsettings.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-clipboard.css" rel="stylesheet" />
<link href="libs/anchor-sections-1.0.1/anchor-sections.css" rel="stylesheet" />
<script src="libs/anchor-sections-1.0.1/anchor-sections.js"></script>
<link rel="stylesheet" href="css/style.css" type="text/css" />
<link rel="stylesheet" href="css/prism.min.css" type="text/css" />
</head>
<body>
<div class="book without-animation with-summary font-size-2 font-family-1" data-basepath=".">
<div class="book-summary">
<nav role="navigation">
<ul class="summary">
<li><a href="./" class="title">Introduction to Programming</a></li>
<li class="divider"></li>
<li class="chapter" data-level="" data-path="index.html"><a href="index.html"><i class="fa fa-check"></i>About this Book</a></li>
<li class="part"><span><b>I Python Basics</b></span></li>
<li class="chapter" data-level="1" data-path="python-intro.html"><a href="python-intro.html"><i class="fa fa-check"></i><b>1</b> Introduction to Python</a>
<ul>
<li class="chapter" data-level="1.1" data-path="python-intro.html"><a href="python-intro.html#programming-with-python"><i class="fa fa-check"></i><b>1.1</b> Programming with Python</a>
<ul>
<li class="chapter" data-level="1.1.1" data-path="python-intro.html"><a href="python-intro.html#versions"><i class="fa fa-check"></i><b>1.1.1</b> Versions</a></li>
</ul></li>
<li class="chapter" data-level="1.2" data-path="python-intro.html"><a href="python-intro.html#running-python-code"><i class="fa fa-check"></i><b>1.2</b> Running Python Code</a>
<ul>
<li class="chapter" data-level="1.2.1" data-path="python-intro.html"><a href="python-intro.html#jupyter-notebooks"><i class="fa fa-check"></i><b>1.2.1</b> Jupyter Notebooks</a></li>
<li class="chapter" data-level="1.2.2" data-path="python-intro.html"><a href="python-intro.html#on-the-command-line"><i class="fa fa-check"></i><b>1.2.2</b> On the Command Line</a></li>
</ul></li>
<li class="chapter" data-level="1.3" data-path="python-intro.html"><a href="python-intro.html#comments"><i class="fa fa-check"></i><b>1.3</b> Comments</a></li>
<li class="chapter" data-level="1.4" data-path="python-intro.html"><a href="python-intro.html#variables"><i class="fa fa-check"></i><b>1.4</b> Variables</a>
<ul>
<li class="chapter" data-level="1.4.1" data-path="python-intro.html"><a href="python-intro.html#data-types"><i class="fa fa-check"></i><b>1.4.1</b> Data Types</a></li>
</ul></li>
<li class="chapter" data-level="1.5" data-path="python-intro.html"><a href="python-intro.html#getting-help"><i class="fa fa-check"></i><b>1.5</b> Getting Help</a></li>
<li class="chapter" data-level="" data-path="python-intro.html"><a href="python-intro.html#resources"><i class="fa fa-check"></i>Resources</a></li>
</ul></li>
<li class="chapter" data-level="2" data-path="functions.html"><a href="functions.html"><i class="fa fa-check"></i><b>2</b> Functions</a>
<ul>
<li class="chapter" data-level="2.1" data-path="functions.html"><a href="functions.html#what-are-functions"><i class="fa fa-check"></i><b>2.1</b> What are Functions?</a></li>
<li class="chapter" data-level="2.2" data-path="functions.html"><a href="functions.html#python-function-syntax"><i class="fa fa-check"></i><b>2.2</b> Python Function Syntax</a>
<ul>
<li class="chapter" data-level="2.2.1" data-path="functions.html"><a href="functions.html#object-methods"><i class="fa fa-check"></i><b>2.2.1</b> Object Methods</a></li>
</ul></li>
<li class="chapter" data-level="2.3" data-path="functions.html"><a href="functions.html#built-in-python-functions"><i class="fa fa-check"></i><b>2.3</b> Built-in Python Functions</a>
<ul>
<li class="chapter" data-level="2.3.1" data-path="functions.html"><a href="functions.html#modules-and-libraries"><i class="fa fa-check"></i><b>2.3.1</b> Modules and Libraries</a></li>
</ul></li>
<li class="chapter" data-level="2.4" data-path="functions.html"><a href="functions.html#writing-functions"><i class="fa fa-check"></i><b>2.4</b> Writing Functions</a>
<ul>
<li class="chapter" data-level="2.4.1" data-path="functions.html"><a href="functions.html#doc-strings"><i class="fa fa-check"></i><b>2.4.1</b> Doc Strings</a></li>
</ul></li>
<li class="chapter" data-level="" data-path="functions.html"><a href="functions.html#resources-1"><i class="fa fa-check"></i>Resources</a></li>
</ul></li>
<li class="chapter" data-level="3" data-path="logic.html"><a href="logic.html"><i class="fa fa-check"></i><b>3</b> Logic and Conditionals</a>
<ul>
<li class="chapter" data-level="3.1" data-path="logic.html"><a href="logic.html#booleans"><i class="fa fa-check"></i><b>3.1</b> Booleans</a>
<ul>
<li class="chapter" data-level="3.1.1" data-path="logic.html"><a href="logic.html#relational-operators"><i class="fa fa-check"></i><b>3.1.1</b> Relational Operators</a></li>
<li class="chapter" data-level="3.1.2" data-path="logic.html"><a href="logic.html#boolean-operators"><i class="fa fa-check"></i><b>3.1.2</b> Boolean Operators</a></li>
</ul></li>
<li class="chapter" data-level="3.2" data-path="logic.html"><a href="logic.html#conditional-statements"><i class="fa fa-check"></i><b>3.2</b> Conditional Statements</a>
<ul>
<li class="chapter" data-level="3.2.1" data-path="logic.html"><a href="logic.html#designing-conditions"><i class="fa fa-check"></i><b>3.2.1</b> Designing Conditions</a></li>
</ul></li>
<li class="chapter" data-level="3.3" data-path="logic.html"><a href="logic.html#determining-module-or-script"><i class="fa fa-check"></i><b>3.3</b> Determining Module or Script</a></li>
<li class="chapter" data-level="" data-path="logic.html"><a href="logic.html#resources-2"><i class="fa fa-check"></i>Resources</a></li>
</ul></li>
<li class="chapter" data-level="4" data-path="lists.html"><a href="lists.html"><i class="fa fa-check"></i><b>4</b> Lists and Sequences</a>
<ul>
<li class="chapter" data-level="4.1" data-path="lists.html"><a href="lists.html#what-is-a-list"><i class="fa fa-check"></i><b>4.1</b> What is a List?</a></li>
<li class="chapter" data-level="4.2" data-path="lists.html"><a href="lists.html#list-indices"><i class="fa fa-check"></i><b>4.2</b> List Indices</a></li>
<li class="chapter" data-level="4.3" data-path="lists.html"><a href="lists.html#list-operations-and-methods"><i class="fa fa-check"></i><b>4.3</b> List Operations and Methods</a></li>
<li class="chapter" data-level="4.4" data-path="lists.html"><a href="lists.html#nested-lists"><i class="fa fa-check"></i><b>4.4</b> Nested Lists</a></li>
<li class="chapter" data-level="4.5" data-path="lists.html"><a href="lists.html#other-sequences"><i class="fa fa-check"></i><b>4.5</b> Other Sequences</a>
<ul>
<li class="chapter" data-level="4.5.1" data-path="lists.html"><a href="lists.html#ranges"><i class="fa fa-check"></i><b>4.5.1</b> Ranges</a></li>
<li class="chapter" data-level="4.5.2" data-path="lists.html"><a href="lists.html#tuples"><i class="fa fa-check"></i><b>4.5.2</b> Tuples</a></li>
</ul></li>
<li class="chapter" data-level="" data-path="lists.html"><a href="lists.html#resources-3"><i class="fa fa-check"></i>Resources</a></li>
</ul></li>
<li class="chapter" data-level="5" data-path="loops.html"><a href="loops.html"><i class="fa fa-check"></i><b>5</b> Iterating with Loops</a>
<ul>
<li class="chapter" data-level="5.1" data-path="loops.html"><a href="loops.html#for-loops"><i class="fa fa-check"></i><b>5.1</b> For Loops</a>
<ul>
<li class="chapter" data-level="5.1.1" data-path="loops.html"><a href="loops.html#variables-and-loops"><i class="fa fa-check"></i><b>5.1.1</b> Variables and Loops</a></li>
</ul></li>
<li class="chapter" data-level="5.2" data-path="loops.html"><a href="loops.html#lists-and-loops"><i class="fa fa-check"></i><b>5.2</b> Lists and Loops</a></li>
<li class="chapter" data-level="5.3" data-path="loops.html"><a href="loops.html#nested-loops"><i class="fa fa-check"></i><b>5.3</b> Nested Loops</a></li>
<li class="chapter" data-level="5.4" data-path="loops.html"><a href="loops.html#list-comprehensions"><i class="fa fa-check"></i><b>5.4</b> List Comprehensions</a></li>
<li class="chapter" data-level="5.5" data-path="loops.html"><a href="loops.html#while-loops"><i class="fa fa-check"></i><b>5.5</b> While Loops</a>
<ul>
<li class="chapter" data-level="5.5.1" data-path="loops.html"><a href="loops.html#counting-with-while-loops"><i class="fa fa-check"></i><b>5.5.1</b> Counting with While Loops</a></li>
<li class="chapter" data-level="5.5.2" data-path="loops.html"><a href="loops.html#sentinels"><i class="fa fa-check"></i><b>5.5.2</b> Sentinels</a></li>
<li class="chapter" data-level="5.5.3" data-path="loops.html"><a href="loops.html#difference-between-for-and-while-loops"><i class="fa fa-check"></i><b>5.5.3</b> Difference Between For and While Loops</a></li>
</ul></li>
<li class="chapter" data-level="5.6" data-path="loops.html"><a href="loops.html#iterating-over-files"><i class="fa fa-check"></i><b>5.6</b> Iterating over Files</a>
<ul>
<li class="chapter" data-level="5.6.1" data-path="loops.html"><a href="loops.html#tryexcept"><i class="fa fa-check"></i><b>5.6.1</b> Try/Except</a></li>
</ul></li>
<li class="chapter" data-level="" data-path="loops.html"><a href="loops.html#resources-4"><i class="fa fa-check"></i>Resources</a></li>
</ul></li>
<li class="chapter" data-level="6" data-path="dictionaries.html"><a href="dictionaries.html"><i class="fa fa-check"></i><b>6</b> Dictionaries</a>
<ul>
<li class="chapter" data-level="6.1" data-path="dictionaries.html"><a href="dictionaries.html#what-is-a-dictionary"><i class="fa fa-check"></i><b>6.1</b> What is a Dictionary?</a></li>
<li class="chapter" data-level="6.2" data-path="dictionaries.html"><a href="dictionaries.html#accessing-a-dictionary"><i class="fa fa-check"></i><b>6.2</b> Accessing a Dictionary</a></li>
<li class="chapter" data-level="6.3" data-path="dictionaries.html"><a href="dictionaries.html#dictionary-methods"><i class="fa fa-check"></i><b>6.3</b> Dictionary Methods</a></li>
<li class="chapter" data-level="6.4" data-path="dictionaries.html"><a href="dictionaries.html#nesting-dictionaries"><i class="fa fa-check"></i><b>6.4</b> Nesting Dictionaries</a></li>
<li class="chapter" data-level="6.5" data-path="dictionaries.html"><a href="dictionaries.html#dictionaries-and-loops"><i class="fa fa-check"></i><b>6.5</b> Dictionaries and Loops</a>
<ul>
<li class="chapter" data-level="6.5.1" data-path="dictionaries.html"><a href="dictionaries.html#dictionary-comprehensions"><i class="fa fa-check"></i><b>6.5.1</b> Dictionary Comprehensions</a></li>
</ul></li>
<li class="chapter" data-level="6.6" data-path="dictionaries.html"><a href="dictionaries.html#which-data-structure-do-i-use"><i class="fa fa-check"></i><b>6.6</b> Which Data Structure Do I Use?</a></li>
<li class="chapter" data-level="" data-path="dictionaries.html"><a href="dictionaries.html#resources-5"><i class="fa fa-check"></i>Resources</a></li>
</ul></li>
<li class="chapter" data-level="7" data-path="searching.html"><a href="searching.html"><i class="fa fa-check"></i><b>7</b> Searching and Filtering</a>
<ul>
<li class="chapter" data-level="7.1" data-path="searching.html"><a href="searching.html#linear-search"><i class="fa fa-check"></i><b>7.1</b> Linear Search</a>
<ul>
<li class="chapter" data-level="7.1.1" data-path="searching.html"><a href="searching.html#maximal-search"><i class="fa fa-check"></i><b>7.1.1</b> Maximal Search</a></li>
<li class="chapter" data-level="7.1.2" data-path="searching.html"><a href="searching.html#falsification-search"><i class="fa fa-check"></i><b>7.1.2</b> Falsification Search</a></li>
</ul></li>
<li class="chapter" data-level="7.2" data-path="searching.html"><a href="searching.html#filtering"><i class="fa fa-check"></i><b>7.2</b> Filtering</a></li>
<li class="chapter" data-level="7.3" data-path="searching.html"><a href="searching.html#mapping"><i class="fa fa-check"></i><b>7.3</b> Mapping</a></li>
<li class="chapter" data-level="7.4" data-path="searching.html"><a href="searching.html#search-efficiency"><i class="fa fa-check"></i><b>7.4</b> Search Efficiency</a>
<ul>
<li class="chapter" data-level="7.4.1" data-path="searching.html"><a href="searching.html#linear-search-speed"><i class="fa fa-check"></i><b>7.4.1</b> Linear Search Speed</a></li>
<li class="chapter" data-level="7.4.2" data-path="searching.html"><a href="searching.html#faster-searching-binary-search"><i class="fa fa-check"></i><b>7.4.2</b> Faster Searching: Binary Search</a></li>
<li class="chapter" data-level="7.4.3" data-path="searching.html"><a href="searching.html#slower-algorithms-sorting"><i class="fa fa-check"></i><b>7.4.3</b> Slower Algorithms: Sorting</a></li>
</ul></li>
<li class="chapter" data-level="" data-path="searching.html"><a href="searching.html#resources-6"><i class="fa fa-check"></i>Resources</a></li>
</ul></li>
<li class="chapter" data-level="8" data-path="functional-programming.html"><a href="functional-programming.html"><i class="fa fa-check"></i><b>8</b> Functional Programming</a>
<ul>
<li class="chapter" data-level="8.1" data-path="functional-programming.html"><a href="functional-programming.html#functions-are-variables"><i class="fa fa-check"></i><b>8.1</b> Functions ARE Variables</a>
<ul>
<li class="chapter" data-level="8.1.1" data-path="functional-programming.html"><a href="functional-programming.html#lambdas-anonymous-functions"><i class="fa fa-check"></i><b>8.1.1</b> lambdas: Anonymous Functions</a></li>
</ul></li>
<li class="chapter" data-level="8.2" data-path="functional-programming.html"><a href="functional-programming.html#functional-looping"><i class="fa fa-check"></i><b>8.2</b> Functional Looping</a>
<ul>
<li class="chapter" data-level="8.2.1" data-path="functional-programming.html"><a href="functional-programming.html#map"><i class="fa fa-check"></i><b>8.2.1</b> Map</a></li>
<li class="chapter" data-level="8.2.2" data-path="functional-programming.html"><a href="functional-programming.html#filter"><i class="fa fa-check"></i><b>8.2.2</b> Filter</a></li>
<li class="chapter" data-level="8.2.3" data-path="functional-programming.html"><a href="functional-programming.html#reduce"><i class="fa fa-check"></i><b>8.2.3</b> Reduce</a></li>
</ul></li>
<li class="chapter" data-level="" data-path="functional-programming.html"><a href="functional-programming.html#resources-7"><i class="fa fa-check"></i>Resources</a></li>
</ul></li>
<li class="part"><span><b>II Specific Libraries</b></span></li>
<li class="chapter" data-level="9" data-path="pandas.html"><a href="pandas.html"><i class="fa fa-check"></i><b>9</b> The <code>pandas</code> Library</a>
<ul>
<li class="chapter" data-level="9.1" data-path="pandas.html"><a href="pandas.html#setting-up-pandas"><i class="fa fa-check"></i><b>9.1</b> Setting up <code>pandas</code></a></li>
<li class="chapter" data-level="9.2" data-path="pandas.html"><a href="pandas.html#series"><i class="fa fa-check"></i><b>9.2</b> Series</a>
<ul>
<li class="chapter" data-level="9.2.1" data-path="pandas.html"><a href="pandas.html#series-operations"><i class="fa fa-check"></i><b>9.2.1</b> Series Operations</a></li>
<li class="chapter" data-level="9.2.2" data-path="pandas.html"><a href="pandas.html#series-methods"><i class="fa fa-check"></i><b>9.2.2</b> Series Methods</a></li>
<li class="chapter" data-level="9.2.3" data-path="pandas.html"><a href="pandas.html#series-indexing"><i class="fa fa-check"></i><b>9.2.3</b> Series Indexing</a></li>
</ul></li>
<li class="chapter" data-level="9.3" data-path="pandas.html"><a href="pandas.html#dataframes"><i class="fa fa-check"></i><b>9.3</b> DataFrames</a>
<ul>
<li class="chapter" data-level="9.3.1" data-path="pandas.html"><a href="pandas.html#dataframe-operations"><i class="fa fa-check"></i><b>9.3.1</b> DataFrame Operations</a></li>
<li class="chapter" data-level="9.3.2" data-path="pandas.html"><a href="pandas.html#dataframe-methods"><i class="fa fa-check"></i><b>9.3.2</b> DataFrame Methods</a></li>
<li class="chapter" data-level="9.3.3" data-path="pandas.html"><a href="pandas.html#accessing-dataframes"><i class="fa fa-check"></i><b>9.3.3</b> Accessing DataFrames</a></li>
</ul></li>
<li class="chapter" data-level="9.4" data-path="pandas.html"><a href="pandas.html#grouping"><i class="fa fa-check"></i><b>9.4</b> Grouping</a>
<ul>
<li class="chapter" data-level="9.4.1" data-path="pandas.html"><a href="pandas.html#aggregation"><i class="fa fa-check"></i><b>9.4.1</b> Aggregation</a></li>
</ul></li>
<li class="chapter" data-level="" data-path="pandas.html"><a href="pandas.html#resources-8"><i class="fa fa-check"></i>Resources</a></li>
</ul></li>
<li class="chapter" data-level="10" data-path="accessing-web-apis.html"><a href="accessing-web-apis.html"><i class="fa fa-check"></i><b>10</b> Accessing Web APIs</a>
<ul>
<li class="chapter" data-level="10.1" data-path="accessing-web-apis.html"><a href="accessing-web-apis.html#web-apis"><i class="fa fa-check"></i><b>10.1</b> Web APIs</a></li>
<li class="chapter" data-level="10.2" data-path="accessing-web-apis.html"><a href="accessing-web-apis.html#restful-requests"><i class="fa fa-check"></i><b>10.2</b> RESTful Requests</a>
<ul>
<li class="chapter" data-level="10.2.1" data-path="accessing-web-apis.html"><a href="accessing-web-apis.html#uris"><i class="fa fa-check"></i><b>10.2.1</b> URIs</a></li>
<li class="chapter" data-level="10.2.2" data-path="accessing-web-apis.html"><a href="accessing-web-apis.html#http-verbs"><i class="fa fa-check"></i><b>10.2.2</b> HTTP Verbs</a></li>
</ul></li>
<li class="chapter" data-level="10.3" data-path="accessing-web-apis.html"><a href="accessing-web-apis.html#accessing-web-apis-1"><i class="fa fa-check"></i><b>10.3</b> Accessing Web APIs</a></li>
<li class="chapter" data-level="10.4" data-path="accessing-web-apis.html"><a href="accessing-web-apis.html#json-data"><i class="fa fa-check"></i><b>10.4</b> JSON Data</a></li>
<li class="chapter" data-level="" data-path="accessing-web-apis.html"><a href="accessing-web-apis.html#resources-9"><i class="fa fa-check"></i>Resources</a></li>
</ul></li>
<li class="appendix"><span><b>Appendix</b></span></li>
<li class="chapter" data-level="A" data-path="installing.html"><a href="installing.html"><i class="fa fa-check"></i><b>A</b> Installing Python</a>
<ul>
<li class="chapter" data-level="A.1" data-path="installing.html"><a href="installing.html#python"><i class="fa fa-check"></i><b>A.1</b> Python</a>
<ul>
<li class="chapter" data-level="A.1.1" data-path="installing.html"><a href="installing.html#anaconda"><i class="fa fa-check"></i><b>A.1.1</b> Anaconda</a></li>
</ul></li>
<li class="chapter" data-level="A.2" data-path="installing.html"><a href="installing.html#text-editors"><i class="fa fa-check"></i><b>A.2</b> Text Editors</a>
<ul>
<li class="chapter" data-level="A.2.1" data-path="installing.html"><a href="installing.html#visual-studio-code"><i class="fa fa-check"></i><b>A.2.1</b> Visual Studio Code</a></li>
<li class="chapter" data-level="A.2.2" data-path="installing.html"><a href="installing.html#atom"><i class="fa fa-check"></i><b>A.2.2</b> Atom</a></li>
<li class="chapter" data-level="A.2.3" data-path="installing.html"><a href="installing.html#sublime-text"><i class="fa fa-check"></i><b>A.2.3</b> Sublime Text</a></li>
<li class="chapter" data-level="A.2.4" data-path="installing.html"><a href="installing.html#pycharm"><i class="fa fa-check"></i><b>A.2.4</b> PyCharm</a></li>
</ul></li>
<li class="chapter" data-level="A.3" data-path="installing.html"><a href="installing.html#command-line-tools-bash"><i class="fa fa-check"></i><b>A.3</b> Command Line Tools (Bash)</a>
<ul>
<li class="chapter" data-level="A.3.1" data-path="installing.html"><a href="installing.html#command-line-on-a-mac"><i class="fa fa-check"></i><b>A.3.1</b> Command Line on a Mac</a></li>
<li class="chapter" data-level="A.3.2" data-path="installing.html"><a href="installing.html#command-line-on-windows"><i class="fa fa-check"></i><b>A.3.2</b> Command Line on Windows</a></li>
</ul></li>
<li class="chapter" data-level="" data-path="installing.html"><a href="installing.html#resources-10"><i class="fa fa-check"></i>Resources</a></li>
</ul></li>
<li class="chapter" data-level="B" data-path="markdown.html"><a href="markdown.html"><i class="fa fa-check"></i><b>B</b> Markdown</a>
<ul>
<li class="chapter" data-level="B.1" data-path="markdown.html"><a href="markdown.html#writing-markdown"><i class="fa fa-check"></i><b>B.1</b> Writing Markdown</a>
<ul>
<li class="chapter" data-level="B.1.1" data-path="markdown.html"><a href="markdown.html#text-formatting"><i class="fa fa-check"></i><b>B.1.1</b> Text Formatting</a></li>
<li class="chapter" data-level="B.1.2" data-path="markdown.html"><a href="markdown.html#text-blocks"><i class="fa fa-check"></i><b>B.1.2</b> Text Blocks</a></li>
</ul></li>
<li class="chapter" data-level="B.2" data-path="markdown.html"><a href="markdown.html#rendering-markdown"><i class="fa fa-check"></i><b>B.2</b> Rendering Markdown</a></li>
<li class="chapter" data-level="" data-path="markdown.html"><a href="markdown.html#resources-11"><i class="fa fa-check"></i>Resources</a></li>
</ul></li>
<li class="chapter" data-level="C" data-path="command-line.html"><a href="command-line.html"><i class="fa fa-check"></i><b>C</b> The Command Line</a>
<ul>
<li class="chapter" data-level="C.1" data-path="command-line.html"><a href="command-line.html#accessing-the-command-line"><i class="fa fa-check"></i><b>C.1</b> Accessing the Command line</a></li>
<li class="chapter" data-level="C.2" data-path="command-line.html"><a href="command-line.html#navigating-the-command-line"><i class="fa fa-check"></i><b>C.2</b> Navigating the Command Line</a>
<ul>
<li class="chapter" data-level="C.2.1" data-path="command-line.html"><a href="command-line.html#changing-directories"><i class="fa fa-check"></i><b>C.2.1</b> Changing Directories</a></li>
<li class="chapter" data-level="C.2.2" data-path="command-line.html"><a href="command-line.html#listing-files"><i class="fa fa-check"></i><b>C.2.2</b> Listing Files</a></li>
<li class="chapter" data-level="C.2.3" data-path="command-line.html"><a href="command-line.html#paths"><i class="fa fa-check"></i><b>C.2.3</b> Paths</a></li>
</ul></li>
<li class="chapter" data-level="C.3" data-path="command-line.html"><a href="command-line.html#file-commands"><i class="fa fa-check"></i><b>C.3</b> File Commands</a>
<ul>
<li class="chapter" data-level="C.3.1" data-path="command-line.html"><a href="command-line.html#learning-new-commands"><i class="fa fa-check"></i><b>C.3.1</b> Learning New Commands</a></li>
<li class="chapter" data-level="C.3.2" data-path="command-line.html"><a href="command-line.html#wildcards"><i class="fa fa-check"></i><b>C.3.2</b> Wildcards</a></li>
</ul></li>
<li class="chapter" data-level="C.4" data-path="command-line.html"><a href="command-line.html#dealing-with-errors"><i class="fa fa-check"></i><b>C.4</b> Dealing With Errors</a></li>
<li class="chapter" data-level="C.5" data-path="command-line.html"><a href="command-line.html#directing-output"><i class="fa fa-check"></i><b>C.5</b> Directing Output</a></li>
<li class="chapter" data-level="C.6" data-path="command-line.html"><a href="command-line.html#shell-scripts"><i class="fa fa-check"></i><b>C.6</b> Shell Scripts</a></li>
<li class="chapter" data-level="" data-path="command-line.html"><a href="command-line.html#resources-12"><i class="fa fa-check"></i>Resources</a></li>
</ul></li>
<li class="chapter" data-level="D" data-path="javascript.html"><a href="javascript.html"><i class="fa fa-check"></i><b>D</b> JavaScript</a>
<ul>
<li class="chapter" data-level="D.1" data-path="javascript.html"><a href="javascript.html#programming-with-javascript"><i class="fa fa-check"></i><b>D.1</b> Programming with JavaScript</a>
<ul>
<li class="chapter" data-level="D.1.1" data-path="javascript.html"><a href="javascript.html#history-and-versions"><i class="fa fa-check"></i><b>D.1.1</b> History and Versions</a></li>
<li class="chapter" data-level="D.1.2" data-path="javascript.html"><a href="javascript.html#running-javascript"><i class="fa fa-check"></i><b>D.1.2</b> Running JavaScript</a></li>
</ul></li>
<li class="chapter" data-level="D.2" data-path="javascript.html"><a href="javascript.html#javascript-basics"><i class="fa fa-check"></i><b>D.2</b> JavaScript Basics</a>
<ul>
<li class="chapter" data-level="D.2.1" data-path="javascript.html"><a href="javascript.html#strict-mode"><i class="fa fa-check"></i><b>D.2.1</b> Strict Mode</a></li>
</ul></li>
<li class="chapter" data-level="D.3" data-path="javascript.html"><a href="javascript.html#variables-1"><i class="fa fa-check"></i><b>D.3</b> Variables</a>
<ul>
<li class="chapter" data-level="D.3.1" data-path="javascript.html"><a href="javascript.html#basic-data-types"><i class="fa fa-check"></i><b>D.3.1</b> Basic Data Types</a></li>
<li class="chapter" data-level="D.3.2" data-path="javascript.html"><a href="javascript.html#type-coercion"><i class="fa fa-check"></i><b>D.3.2</b> Type Coercion</a></li>
<li class="chapter" data-level="D.3.3" data-path="javascript.html"><a href="javascript.html#arrays"><i class="fa fa-check"></i><b>D.3.3</b> Arrays</a></li>
<li class="chapter" data-level="D.3.4" data-path="javascript.html"><a href="javascript.html#objects"><i class="fa fa-check"></i><b>D.3.4</b> Objects</a></li>
</ul></li>
<li class="chapter" data-level="D.4" data-path="javascript.html"><a href="javascript.html#control-structures"><i class="fa fa-check"></i><b>D.4</b> Control Structures</a>
<ul>
<li class="chapter" data-level="D.4.1" data-path="javascript.html"><a href="javascript.html#conditionals"><i class="fa fa-check"></i><b>D.4.1</b> Conditionals</a></li>
<li class="chapter" data-level="D.4.2" data-path="javascript.html"><a href="javascript.html#loops-1"><i class="fa fa-check"></i><b>D.4.2</b> Loops</a></li>
</ul></li>
<li class="chapter" data-level="D.5" data-path="javascript.html"><a href="javascript.html#functions-1"><i class="fa fa-check"></i><b>D.5</b> Functions</a>
<ul>
<li class="chapter" data-level="D.5.1" data-path="javascript.html"><a href="javascript.html#functional-programming-1"><i class="fa fa-check"></i><b>D.5.1</b> Functional Programming</a></li>
</ul></li>
<li class="chapter" data-level="" data-path="javascript.html"><a href="javascript.html#resources-13"><i class="fa fa-check"></i>Resources</a></li>
</ul></li>
<li class="divider"></li>
<li><a href="https://github.com/rstudio/bookdown" target="blank">Published with bookdown</a></li>
</ul>
</nav>
</div>
<div class="book-body">
<div class="body-inner">
<div class="book-header" role="navigation">
<h1>
<i class="fa fa-circle-o-notch fa-spin"></i><a href="./">Introduction to Programming</a>
</h1>
</div>
<div class="page-wrapper" tabindex="-1" role="main">
<div class="page-inner">
<section class="normal" id="section-">
<div id="functional-programming" class="section level1" number="8">
<h1><span class="header-section-number">Chapter 8</span> Functional Programming</h1>
<p>This chapter introduces techniques from <strong>Functional Programming</strong>, which is a programming paradigm centered on <em>functions</em> rather than on <em>variables</em> and statements as you’ve been doing so far (known as <em>imperative programming</em>). Functional programming offers another way to think about giving “instructions” to a computer, which can make it easier to think about and implement some algorithms. While not a completely functional language, Python does contain a number of “functional-programming-like” features that can be mixed with the imperative strategies we’re used to, allowing for more compact, readable, and “Pythonic” code in some cases.</p>
<div id="functions-are-variables" class="section level2" number="8.1">
<h2><span class="header-section-number">8.1</span> Functions ARE Variables</h2>
<p>Previously we’ve described functions as “named sequences of instructions”, or groupings of lines of code that are given a name. But in a functional programming paradigm, functions are <em>first-class objects</em>—that is, they are “things” (values) that can be organized and manipulated <em>just like variables</em>.</p>
<p>In Python, <strong>functions ARE variables</strong>:</p>
<pre class="language-python"><code><span class="token comment"># create a function called `say_hello`</span>
<span class="token keyword">def</span> <span class="token function">say_hello</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Hello, "</span><span class="token operator">+</span>name<span class="token punctuation">)</span>
<span class="token comment"># what kind of thing is `say_hello` ?</span>
<span class="token builtin">type</span><span class="token punctuation">(</span>say_hello<span class="token punctuation">)</span> <span class="token comment"># <class 'function'></span></code></pre>
<p>Just like <code>x = 3</code> defines a variable for a value of type <code>int</code>, or <code>msg = "hello"</code> defines a variable for a value of type <code>string</code>, the above <code>say_hello</code> function is actually a variable for a <em>value</em> of type <code>function</code>!</p>
<div class="alert alert-warning">
<p>Note that we refer to the function by its name <em>without</em> the parentheses!</p>
</div>
<div class="alert alert-info">
<p>This is why it is possible to accidentally “overwrite” built-in functions by assigning values to variables like <code>sum</code>, <code>max</code>, or <code>dict</code>.</p>
</div>
<p>The fact that functions <strong>are</strong> variables is the core realization to make when programming in a functional style. You need to be able to think about functions as <strong>things</strong> (nouns), rather than as <strong>behaviors</strong> (verbs). If you imagine that functions are “recipes”, then you need to think about them as <em>pages from the cookbook</em> (that can be bound together or handed to a friend), rather than just the sequence of actions that they tell you to perform.</p>
<p>And because functions are just another type of variable, they can be used <strong>anywhere</strong> that a “regular” variable can be used. For example, functions are values, so they can be assigned to other variables!</p>
<pre class="language-python"><code><span class="token comment"># Create a function `say_hello`</span>
<span class="token keyword">def</span> <span class="token function">say_hello</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Hello, "</span><span class="token operator">+</span>name<span class="token punctuation">)</span>
<span class="token comment"># Assign the `say_hello` value to a new variable `greet`</span>
greet <span class="token operator">=</span> say_hello
<span class="token comment"># Call the function assigned to the `greet` variable</span>
greet<span class="token punctuation">(</span><span class="token string">"world"</span><span class="token punctuation">)</span> <span class="token comment"># prints "Hello world"</span></code></pre>
<p>It helps to think of functions as just a special kind of list. Just as <em>lists</em> have a special syntax <code>[]</code> (bracket notation) that can be used to “get” a value from the list, <em>functions</em> have a special syntax <code>()</code> (parentheses) that can be used to “call” and run the function.</p>
<p>Moreover, functions are values, so they can be <em>passed as parameters to other functions</em>!</p>
<pre class="language-python"><code><span class="token comment"># Create a function `say_hello`</span>
<span class="token keyword">def</span> <span class="token function">say_hello</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Hello, "</span><span class="token operator">+</span>name<span class="token punctuation">)</span>
<span class="token comment"># A function that takes ANOTHER FUNCTION as an argument</span>
<span class="token comment"># This function will call the argument function, passing it "world"</span>
<span class="token keyword">def</span> <span class="token function">do_with_world</span><span class="token punctuation">(</span>func_to_call<span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token comment"># call the given function with an argument of "world"</span>
func_to_call<span class="token punctuation">(</span><span class="token string">"world"</span><span class="token punctuation">)</span>
<span class="token comment"># Call `do_with_world`, saying the "thing to do" is `say_hello`</span>
do_with_world<span class="token punctuation">(</span>say_hello<span class="token punctuation">)</span> <span class="token comment"># prints "Hello world"</span></code></pre>
<p>In this case, the <code>do_with_world</code> function will <em>call</em> whatever function it is given, passing in a value of <code>"world"</code>. (You can think of this as similar to having a function that accesses the <code>'world'</code> key of a given dictionary).</p>
<p><strong>Important note</strong>: when you pass <code>say_hello</code> as an argument, you don’t put any parentheses after it! Putting the parentheses after the function name <em>calls</em> the function, causing it to perform the lines of code it defines. This will cause the expression containing the function to <em>resolve</em> to its returned value, rather than being the function value itself. It’s like passing in the baked cake rather than the recipe page.</p>
<pre class="language-python"><code><span class="token keyword">def</span> <span class="token function">greet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token comment"># version with no args</span>
<span class="token keyword">return</span> <span class="token string">"Hello"</span>
<span class="token comment"># Print out the function</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>greet<span class="token punctuation">)</span> <span class="token comment"># prints <function greet>, the function</span>
<span class="token comment"># Resolve the expression, then print that out</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>greet<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment"># prints "Hello", which is what `greet()` resolves to.</span></code></pre>
<p>A function that is passed into another is commonly referred to as a <strong>callback function</strong>: it is an argument that the other function will “call back to” and execute when needed.</p>
<p>Functions can take more than one <em>callback function</em> as arguments, which can be a useful way of <em>composing</em> behaviors.</p>
<pre class="language-python"><code><span class="token keyword">def</span> <span class="token function">do_at_once</span><span class="token punctuation">(</span>first_callback<span class="token punctuation">,</span> second_callback<span class="token punctuation">)</span><span class="token punctuation">:</span>
first_callback<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment"># execute the first function</span>
second_callback<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment"># execute the second function</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"at the same time! "</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">pat_head</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"pat your head"</span><span class="token punctuation">,</span> end<span class="token operator">=</span><span class="token string">" "</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">rub_belly</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"rub your belly"</span><span class="token punctuation">,</span> end<span class="token operator">=</span><span class="token string">" "</span><span class="token punctuation">)</span>
<span class="token comment"># Pass in the callbacks to "do at once"</span>
do_at_once<span class="token punctuation">(</span>pat_head<span class="token punctuation">,</span> rub_belly<span class="token punctuation">)</span></code></pre>
<p>This idea of <em>passing functions are arguments to other functions</em> is at the heart of functional programming, and is what gives it expressive power: you can define program behavior primarily in terms of the behaviors that are run, and less in terms of the data variables used.</p>
<div id="lambdas-anonymous-functions" class="section level3" number="8.1.1">
<h3><span class="header-section-number">8.1.1</span> lambdas: Anonymous Functions</h3>
<p>You have previously used <strong>anonymous variables</strong> in your programs, or values which are not assigned a variable name (so remain anonymous). These values were defined as <em>literals</em> or expressions and passed directly into functions, rather than assigning them to variables:</p>
<pre class="language-python"><code>my_list <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">]</span> <span class="token comment"># a named variable (not anonymous)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>my_list<span class="token punctuation">)</span> <span class="token comment"># pass in non-anonymous variable</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token comment"># pass in anonymous value</span></code></pre>
<p>Because functions <strong>are</strong> variables, it is also possible to define <strong>anonymous functions</strong>: functions that are not given a name, but instead are passed directly into other functions. In Python, these anonymous functions are referred to as <strong>lambdas</strong> (named after <a href="https://en.wikipedia.org/wiki/Lambda_calculus">lambda calculus</a>, which is a way of defining algorithms in terms of functions).</p>
<p>Lambdas are written using the following general syntax:</p>
<pre class="language-python"><code><span class="token keyword">lambda</span> arg1<span class="token punctuation">,</span> arg2<span class="token punctuation">:</span> expression_to_return</code></pre>
<p>You indicate that you are defining a lambda function with the keyword <code>lambda</code> (rather than the keyword <code>def</code> used for named functions). This is followed by a list of arguments separated by commas (what normally goes inside the <code>()</code> parentheses in a named function definition), then a colon <code>:</code>, then the expression that will be <em>returned</em> by the anonymous function.</p>
<p>For example, compare the following named and anonymous function definitions:</p>
<pre class="language-python"><code><span class="token comment"># Named function to square a value</span>
<span class="token keyword">def</span> <span class="token function">square</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token keyword">return</span> x<span class="token operator">**</span><span class="token number">2</span>
<span class="token comment"># Anonymous function to square a value</span>
<span class="token keyword">lambda</span> x<span class="token punctuation">:</span> x<span class="token operator">**</span><span class="token number">2</span>
<span class="token comment"># Named function to combine first and last name</span>
<span class="token keyword">def</span> <span class="token function">make_full_name</span><span class="token punctuation">(</span>first<span class="token punctuation">,</span> last<span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token keyword">return</span> first <span class="token operator">+</span> <span class="token string">" "</span> <span class="token operator">+</span> last
<span class="token comment"># Anonymous function to combine first and last name</span>
<span class="token keyword">lambda</span> first<span class="token punctuation">,</span> last<span class="token punctuation">:</span> first <span class="token operator">+</span> <span class="token string">" "</span> <span class="token operator">+</span> last</code></pre>
<p>You’re basically replacing <code>def</code> and the function name with the word <code>lambda</code>, removing the parentheses around the arguments, and removing the <code>return</code> keyword!</p>
<p>Just as other expressions can be assigned to variables, lambda functions can be assigned to variables in order to give them a name. This is the equivalent of having defined them as named functions in the first place:</p>
<pre class="language-python"><code>square <span class="token operator">=</span> <span class="token keyword">lambda</span> x<span class="token punctuation">:</span> x<span class="token operator">**</span><span class="token number">2</span>
make_full_name <span class="token operator">=</span> <span class="token keyword">lambda</span> first<span class="token punctuation">,</span> last<span class="token punctuation">:</span> first <span class="token operator">+</span> <span class="token string">" "</span> <span class="token operator">+</span> last</code></pre>
<p>There is one major restriction on what kind of functions can be defined as anonymous lambdas: they must be functions that consist of <strong>only</strong> a single returned expression. That is, they need to be a function that contains exactly one line of code, which is a <code>return</code> statement (as in the above examples). This means that lambdas are <strong><em>short</em></strong> functions that usually perform very simple transformations to the arguments… exactly what you want to do with functional programming!</p>
</div>
</div>
<div id="functional-looping" class="section level2" number="8.2">
<h2><span class="header-section-number">8.2</span> Functional Looping</h2>
<p>Why should you care about treating functions as variables, or defining anonymous lambda functions? Because doing so allows you to <em>replace loops with function calls</em> in some situations. For particular kinds of loops, this can make the code more <em>expressive</em> (more clearly indicative of what it is doing).</p>
<div id="map" class="section level3" number="8.2.1">
<h3><span class="header-section-number">8.2.1</span> Map</h3>
<p>For example, consider the following loop:</p>
<pre class="language-python"><code><span class="token keyword">def</span> <span class="token function">square</span><span class="token punctuation">(</span>n<span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token comment"># a function that squares a number</span>
<span class="token keyword">return</span> n<span class="token operator">**</span><span class="token number">2</span>
numbers <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">]</span> <span class="token comment"># an initial list</span>
squares <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token comment"># the transformed list</span>
<span class="token keyword">for</span> number <span class="token keyword">in</span> numbers<span class="token punctuation">:</span>
transformed <span class="token operator">=</span> square<span class="token punctuation">(</span>number<span class="token punctuation">)</span>
squares<span class="token punctuation">.</span>append<span class="token punctuation">(</span>transformed<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>squares<span class="token punctuation">)</span> <span class="token comment"># [1, 4, 9, 16, 25]</span></code></pre>
<p>This loop represents a <strong>mapping</strong> operation: it takes an original list (e.g., of numbers 1 to 5) and produces a <em>new</em> list with each of the original elements transformed in a certain way (e.g., squared). This is a common operation to apply: maybe you want to “transform” a list so that all the values are rounded or lowercase, or you want to <em>map</em> a list of words to a list of their lengths. It is possible to make these changes uses the same pattern as above: create an empty list, then loop through the original list and <code>append</code> the transformed values to the new list.</p>
<p>However, Python also provides a <em>built-in function</em> called <strong><code>map()</code></strong> that directly performs this kind of mapping operation on a list without needing to use a loop:</p>
<pre class="language-python"><code><span class="token keyword">def</span> <span class="token function">square</span><span class="token punctuation">(</span>n<span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token comment"># a function that squares a number</span>
<span class="token keyword">return</span> n<span class="token operator">**</span><span class="token number">2</span>
numbers <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">]</span> <span class="token comment"># an initial list</span>
squares <span class="token operator">=</span> <span class="token builtin">list</span><span class="token punctuation">(</span><span class="token builtin">map</span><span class="token punctuation">(</span>square<span class="token punctuation">,</span> numbers<span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>squares<span class="token punctuation">)</span> <span class="token comment"># [1, 4, 9, 16, 25]</span></code></pre>
<p>The <code>map()</code> function takes a list and produces a <em>new</em> list with each of the elements transformed. The <code>map()</code> function should be passed two arguments: the second is the list to transform, and the first is the <em>name of a callback function</em> that will do the transformation. This callback function must take in a <em>single</em> argument (an element to transform) and return a value (the transformed element).</p>
<p>Note that in Python 3, the <code>map()</code> function returns an <em>iterator</em>, which is a list-like sequence similar to that returned by a dictionary’s <code>keys()</code> or <code>items()</code> methods. Thus in order to interact with it as a list, it needs to be converted using the <code>list()</code> function.</p>
<p>The <code>map()</code> callback function (e.g., <code>square()</code> in the above example) can also be specified using an anonymous lambda, which allows for concisely written code (but often at the expense of readability—see <em>List Comprehensions</em> below for a more elegant, Pythonic solution).</p>
<pre class="language-python"><code>numbers <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">]</span> <span class="token comment"># an initial list</span>
squares <span class="token operator">=</span> <span class="token builtin">list</span><span class="token punctuation">(</span><span class="token builtin">map</span><span class="token punctuation">(</span><span class="token keyword">lambda</span> n<span class="token punctuation">:</span>n<span class="token operator">**</span><span class="token number">2</span><span class="token punctuation">,</span> numbers<span class="token punctuation">)</span><span class="token punctuation">)</span></code></pre>
</div>
<div id="filter" class="section level3" number="8.2.2">
<h3><span class="header-section-number">8.2.2</span> Filter</h3>
<p>A second common operation is to <strong>filter</strong> a list of elements, removing elements that you don’t want (or more accurately: only keeping elements that you DO want). For example, consider the following loop:</p>
<pre class="language-python"><code><span class="token keyword">def</span> <span class="token function">is_even</span><span class="token punctuation">(</span>n<span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token comment"># a function that determines if a number is even</span>
remainder <span class="token operator">=</span> n <span class="token operator">%</span> <span class="token number">2</span> <span class="token comment"># get remainder when dividing by 2 (modulo operator)</span>
<span class="token keyword">return</span> remainder <span class="token operator">==</span> <span class="token number">0</span> <span class="token comment"># True if no remainder, False otherwise</span>
numbers <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">7</span><span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">8</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">]</span> <span class="token comment"># an initial list</span>
evens <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token comment"># the filtered list</span>
<span class="token keyword">for</span> number <span class="token keyword">in</span> numbers<span class="token punctuation">:</span>
<span class="token keyword">if</span> is_even<span class="token punctuation">(</span>number<span class="token punctuation">)</span><span class="token punctuation">:</span>
evens<span class="token punctuation">.</span>append<span class="token punctuation">(</span>number<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>evens<span class="token punctuation">)</span> <span class="token comment"># [2, 8]</span></code></pre>
<p>With this <strong>filtering</strong> loop, we are <em>keeping</em> the values for which the <code>is_even()</code> function returns true (the function determines “what to let in” not “what to keep out”), which we do by appending the “good” values to a new list.</p>
<p>Similar to <code>map()</code>, Python provides a <em>built-in function</em> called <strong><code>filter()</code></strong> that will directly perform this filtering:</p>
<pre class="language-python"><code><span class="token keyword">def</span> <span class="token function">is_even</span><span class="token punctuation">(</span>n<span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token comment"># a function that determines if a number is even</span>
<span class="token keyword">return</span> <span class="token punctuation">(</span>n <span class="token operator">%</span> <span class="token number">2</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span> <span class="token comment"># True if no remainder, False otherwise</span>
numbers <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">7</span><span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">8</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">]</span> <span class="token comment"># an initial list</span>
evens <span class="token operator">=</span> <span class="token builtin">list</span><span class="token punctuation">(</span><span class="token builtin">filter</span><span class="token punctuation">(</span>is_even<span class="token punctuation">,</span> numbers<span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>evens<span class="token punctuation">)</span> <span class="token comment"># [2, 8]</span></code></pre>
<p>The <code>filter()</code> function takes a list and produces a <em>new</em> list that contains only the elements that <em>do match</em> a specific criteria. The <code>filter()</code> function takes in two arguments: the second is the list to filter, and the first is the <em>name of a callback function</em> that will do the filtering. This callback function must take in a <em>single</em> argument (an element to consider) and return <code>True</code> if the element should be included in the filtered list (or <code>False</code> if it should not be included).</p>
<p>Because <code>map()</code> and <code>filter()</code> both produce list-like sequences, it is possible to take the returned value from one function and pass it in as the argument to the next. For example:</p>
<pre class="language-python"><code>numbers <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">,</span><span class="token number">6</span><span class="token punctuation">]</span>
<span class="token comment"># Get the squares of EVEN numbers only</span>
filtered <span class="token operator">=</span> <span class="token builtin">filter</span><span class="token punctuation">(</span>is_even<span class="token punctuation">,</span> numbers<span class="token punctuation">)</span> <span class="token comment"># filter the numbers</span>
squares <span class="token operator">=</span> <span class="token builtin">map</span><span class="token punctuation">(</span>square<span class="token punctuation">,</span> filtered<span class="token punctuation">)</span> <span class="token comment"># map the filtered values</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token builtin">list</span><span class="token punctuation">(</span>squares<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment"># [4, 16, 36]</span>
<span class="token comment"># Or in one statement, passing results anonymously</span>
squares <span class="token operator">=</span> <span class="token builtin">map</span><span class="token punctuation">(</span>square<span class="token punctuation">,</span>
<span class="token builtin">filter</span><span class="token punctuation">(</span>is_even<span class="token punctuation">,</span>
numbers<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment"># watch out for the parentheses!</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token builtin">list</span><span class="token punctuation">(</span>squares<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment"># [4, 16, 36]</span></code></pre>
<p>This structure can potentially make it easier to understand the code’s intent: it is “<code>square</code>ing the <code>is_even</code> <code>numbers</code>”!</p>
</div>
<div id="reduce" class="section level3" number="8.2.3">
<h3><span class="header-section-number">8.2.3</span> Reduce</h3>
<p>The third important operation in functional programming (besides <em>mapping</em> and <em>filtering</em>) is <strong>reducing</strong> a list. Reducing a list means to <em>aggregate</em> that lists values together, transforming the list into a single value. For example, the built-in <code>sum()</code> function is a <em>reducing</em> operation (and in fact, the most common one!): it reduces a list of numbers to a single summed value. Thus you can think of <code>reduce()</code> as a <em>generalization</em> of the <code>sum()</code> function—but rather than just adding (<code>+</code>) the values together, <code>reduce()</code> allows you to specify what operation to perform when aggregating (e.g., <a href="https://en.wikipedia.org/wiki/Factorial">multiplication</a>).</p>
<p>Because the <code>reduce()</code> function can be complex to interpret, it was actually <em>removed</em> from the set of “core” built-in functions in Python 3 and relegated to the <code>functools</code> module. Thus you need to import the function in order to use it:</p>
<pre class="language-python"><code><span class="token keyword">from</span> functools <span class="token keyword">import</span> <span class="token builtin">reduce</span></code></pre>
<p>To understand how a <em>reduce</em> operation works, consider the following basic loop:</p>
<pre class="language-python"><code><span class="token keyword">def</span> <span class="token function">add_twice</span><span class="token punctuation">(</span>initial<span class="token punctuation">,</span> new_amount<span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token comment"># a function that adds a second number twice</span>
<span class="token keyword">return</span> initial <span class="token operator">+</span> new_amount <span class="token operator">+</span> new_amount
numbers <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">]</span> <span class="token comment"># an initial list</span>
running_total <span class="token operator">=</span> <span class="token number">0</span> <span class="token comment"># an accumulated aggregate</span>
<span class="token keyword">for</span> number <span class="token keyword">in</span> numbers<span class="token punctuation">:</span>
running_total <span class="token operator">=</span> add_twice<span class="token punctuation">(</span>running_total<span class="token punctuation">,</span> number<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>running_total<span class="token punctuation">)</span> <span class="token comment"># 30 (0+2*1+2*2+2*3+2*4+2*5)</span></code></pre>
<p>This loop <strong>reduces</strong> the list into an “accumulated” product (factorial) of all the numbers in the list. Inside the loop, the <code>multiply()</code> function is called and passed the “current total” and the “new value” to be combined into the aggregate (<em>in that order</em>). The resulting total is then reassigned as the “current total” for the next iteration.</p>
<p>The <strong><code>reduce()</code></strong> function does exactly this work: it takes as arguments a <em>callback</em> function used to combine the current running total with the new value, and a list of values to combine. Whereas the <code>map()</code> and <code>filter()</code> callback functions each took 1 argument, the <code>reduce()</code> callback function requires <strong>2</strong> arguments: the first will be the “running total”, and the second will be the “new value” to mix into the aggregate. (While this ordering doesn’t influence the factorial example, it is relevant for other operations):</p>
<pre class="language-python"><code><span class="token keyword">def</span> <span class="token function">add_twice</span><span class="token punctuation">(</span>initial<span class="token punctuation">,</span> new_amount<span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token comment"># a function that adds a second number twice</span>
<span class="token keyword">return</span> initial <span class="token operator">+</span> new_amount <span class="token operator">+</span> new_amount
numbers <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">]</span> <span class="token comment"># an initial list</span>
product <span class="token operator">=</span> <span class="token builtin">reduce</span><span class="token punctuation">(</span>add_twice<span class="token punctuation">,</span> numbers<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token comment"># start aggregating with 0</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>running_total<span class="token punctuation">)</span> <span class="token comment"># 30 (0+2*1+2*2+2*3+2*4+2*5)</span></code></pre>
<p>Note that the <code>reduce()</code> function aggregates into a single value, so the result doesn’t need to be converted from an <em>iterator</em> to a list!</p>
<p>To summarize, the <code>map()</code>, <code>filter()</code>, and <code>reduce()</code> operations work as follows:</p>
<div class="figure">
<img src="img/functional-programming/map-filter-reduce-in-emoji-python.png" alt="" />
<p class="caption">Map, filter, reduce explained with emoji.</p>
</div>
<p>All together, the <strong>map</strong>, <strong>filter</strong>, and <strong>reduce</strong> operations form the basis for a functional consideration of a program. Indeed, these kinds of operations are very common when discussing data manipulations: for example, the famous <a href="https://en.wikipedia.org/wiki/MapReduce">MapReduce</a> model involves “mapping” each element through a complex function (on a different computer no less!), and then “reducing” the results into a single answer.</p>
</div>
</div>
<div id="resources-7" class="section level2 unnumbered">
<h2>Resources</h2>
<div class="list-condensed">
<ul>
<li><a href="https://www.ibm.com/developerworks/library/l-prog/">Functional Programming in Python (IBM)</a> (note: Python 2)</li>
<li><a href="http://www.u.arizona.edu/~erdmann/mse350/topics/list_comprehensions.html">Map, Filter, Lambda, and List Comprehensions in Python</a> (note: Python 2)</li>
<li><a href="http://www.oreilly.com/programming/free/files/functional-programming-python.pdf">Functional Programming in Python (O’Reilly)</a> (short eBook)</li>
<li><a href="https://docs.python.org/3/howto/functional.html">Functional Programming HOWTO</a> (advanced, not recommended)</li>
</ul>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
<a href="searching.html" class="navigation navigation-prev " aria-label="Previous page"><i class="fa fa-angle-left"></i></a>
<a href="pandas.html" class="navigation navigation-next " aria-label="Next page"><i class="fa fa-angle-right"></i></a>
</div>
</div>
<script src="libs/gitbook-2.6.7/js/app.min.js"></script>
<script src="libs/gitbook-2.6.7/js/clipboard.min.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-search.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-sharing.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-fontsettings.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-bookdown.js"></script>
<script src="libs/gitbook-2.6.7/js/jquery.highlight.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-clipboard.js"></script>
<script>
gitbook.require(["gitbook"], function(gitbook) {
gitbook.start({
"sharing": {
"github": true,
"facebook": false,
"twitter": false,
"linkedin": false,
"weibo": false,
"instapaper": false,
"vk": false,
"whatsapp": false,
"all": ["github", "facebook", "twitter", "google"],
"google": false
},
"fontsettings": {
"theme": "white",
"family": "sans",
"size": 2
},
"edit": {
"link": "https://github.com/infx511/book/edit/master/functional-programming.Rmd",
"text": "Edit"
},
"history": {
"link": null,
"text": null
},
"view": {
"link": null,
"text": null
},
"download": null,
"search": {
"engine": "fuse",
"options": null
},
"toc": {
"collapse": "section",
"scroll_highlight": true
}
});
});
</script>
</body>
</html>