-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.html
776 lines (540 loc) · 15.4 KB
/
index.html
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Functional Programming is not just Lambda Functions</title>
<meta name="description" content="">
<meta name="author" content="David Sferruzza">
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/sp.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match(/print-pdf/gi) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName('head')[0].appendChild(link);
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class="reveal">
<div class="slides">
<section data-markdown data-separator="^\r?\n---\r?\n$">
<textarea data-template>
# Functional Programming is not just Lambda Functions
## David Sferruzza
### 2017-06-08
---
# About me
- [@d_sferruzza](https://twitter.com/d_sferruzza)
- [github.com/dsferruzza](https://github.com/dsferruzza)
- Head of Research and Development at [Startup Palace](https://www.startup-palace.com)
- PhD student in software engineering at *University of Nantes*
![](img/sp.gif) <!-- .element: class="stretch" -->
---
# FP is for Functional Programming
> FP is a **declarative** programming paradigm, which means programming is done with **expressions**.
It is becoming more and more popular.
![](img/fp.png) <!-- .element: class="stretch" -->
---
# Declarative vs. imperative
> **Imperative programming**: use statements that change a program's state
>
> **Declarative programming**: express the logic of a computation without describing its control flow
- imperative: shopping instructions
- declarative: shopping list
---
# Lambda functions
*also called __anonymous function__*
```javascript
// ▼ regular function
function myFunction(foo) {
return foo + 1;
}
// ▼ lambda function
var myLambdaFunction = function(foo) {
return foo + 1;
}
// ▼ lambda function
var myLambdaFunction = foo => foo + 1;
```
---
# λ-calculus
- Alonzo Church (1930s)
- formal system for expressing computation
- equivalent to the Turing machine
![](img/lambda-calculus.jpg) <!-- .element: class="stretch" -->
<small>See: [The Lambda Calculus and The JavaScript](http://fr.slideshare.net/normanrichards/the-lambda-calculus-and-the-javascript)</small>
---
# Learning FP is like...
- learning **new ways to think** about programming
- **writting better code** right now
- even with *non-functional* languages
![](img/reindeer.gif) <!-- .element: class="stretch" -->
Languages that allow to use some **FP concepts**:
- FP languages (Haskell, Scala, Erlang, ...)
- a lot of *non-FP* languages \o/ (like JS)
---
# Concepts
Let's explore some FP concepts:
- referential transparency
- higher-order functions
- lazy evaluation
- immutability
and apply them with JS!
---
# Impure function
```javascript
function divideByTwo(number) {
var rightNow = new Date();
launchNuke(rightNow);
return number / 2;
}
```
This function has *observable* **side-effects** (obviously).
But this can't be guessed by looking to its signature.
So we need to be very careful when manipulating it!
![](img/fail.gif) <!-- .element: class="stretch" -->
---
# Pure function
```javascript
function addFive(number) {
return number + 5;
}
```
This function has no side-effects.
It **always** returns the same result when given the same arguments.
```javascript
addFive(-4) === addFive(-4)
```
![](img/excellent.gif) <!-- .element: class="stretch" -->
---
# Referential transparency
> An expression is said to be referentially transparent if it can be replaced with its corresponding value without changing the program's behavior.
Using pure functions allows to **reason** on programs as if they were equations.
![](img/mindblown.gif) <!-- .element: class="stretch" -->
---
# Advice
## Build your programs with pure functions wherever possible
Business logic should be reliable and easily testable.
## Isolate functions with side-effects
We want to know which functions can make side-effects, so we can be careful when calling them.
---
# Concepts
- ~~referential transparency~~
- higher-order functions
- lazy evaluation
- immutability
---
# Higher-order functions
An higher-order function is just a function that verifies at least one of the following properties:
- it takes one or more functions as arguments
- it returns a function as its result
![](img/inception.gif) <!-- .element: class="stretch" -->
---
# Example
```javascript
function applyTwice(f, x) {
return f(f(x));
}
// ^ takes a function as argument
function timesThree(x) {
return x * 3;
}
applyTwice(timesThree, 7);
// timesThree(timesThree(7))
// timesThree(21)
// 63
```
---
# What's the point?
- having a good *separation of concerns*
- creating complex functions by composing simple functions
![](img/lego.gif) <!-- .element: class="stretch" -->
---
# Play time!
Let's apply our knowledge of higher-order functions by manipulating JS arrays and magical ponies!
![](img/party.gif) <!-- .element: class="stretch" -->
---
# Context
```javascript
var ponies = [
{ name: "Rainbow Dash", color: "purple",
flying: true },
{ name: "Applejack", color: "orange",
flying: false },
{ name: "Fluttershy", color: "yellow",
flying: true },
];
```
We want to get a list of strings formatted like this:
`name (color)`
---
# Context
We will write a `displayPonies` function so that:
```javascript
displayPonies(ponies);
// [ "Rainbow Dash (purple)",
// "Applejack (orange)",
// "Fluttershy (yellow)" ]
```
---
# Imperative solution
```javascript
function displayPonies(ponies) {
for (var i = 0; i < ponies.length; i++) {
ponies[i] = ponies[i].name +
" (" + ponies[i].color + ")";
}
return ponies;
}
```
We are mixing 2 behaviors:
- iterating on an array
- transforming our data
---
# Array.map
```javascript
function displayPonies(ponies) {
function transformation(pony) {
return pony.name +
" (" + pony.color + ")";
}
return ponies.map(transformation);
}
```
- `Array.map` handles array iteration for us \o/
- we handle the transformation
---
# With ES6 syntax
Let's use *lambda functions* and *template strings*!
```javascript
ponies.map(p => `${p.name} (${p.color})`);
// [ "Rainbow Dash (purple)",
// "Applejack (orange)",
// "Fluttershy (yellow)" ]
```
![](img/shocked.gif) <!-- .element: class="stretch" -->
---
# Array.filter
```javascript
ponies.filter(function(pony) {
// If a pony cannot fly, return true
// If it can, return false
return !pony.flying;
});
// [ { name: "Applejack", color: "orange",
// flying: false } ]
```
---
# Let's chain!
```javascript
ponies.filter(function(pony) {
return pony.flying;
}).map(function(pony) {
return pony.name + " (" + pony.color + ")";
});
// [ "Rainbow Dash (purple)",
// "Fluttershy (yellow)" ]
```
*Reminder: `Array.map` and `Array.filter` are higher-order functions.*
---
# Array.reduce
```javascript
var people = [
{ name: "Bruce", age: 30 },
{ name: "Tony", age: 35 },
{ name: "Peter", age: 26 },
];
people.reduce(function(acc, cur) {
return acc + cur.age;
}, 0);
// --> 91
```
---
# Array.reduce
```javascript
function map(array, transformation) {
return array.reduce(function(acc, cur) {
acc.push(transformation(cur));
return acc;
}, []);
}
function filter(array, predicate) {
return array.reduce(function(acc, cur) {
if (predicate(cur)) acc.push(cur);
return acc;
}, []);
}
```
---
# Advice
Avoid using loops to manipulate arrays.
## Cheat sheet
If you have an array and you want to:
- apply a transformation to each of its elements (keeping their order/number): **map**
- remove some of its elements (keeping order and value of the others): **filter**
- scan it to build a new data structure: **fold/reduce**
---
# Concepts
- ~~referential transparency~~
- ~~higher-order functions~~
- lazy evaluation
- immutability
---
# Evaluation strategy
- **when** to evaluate the arguments of a function call?
- **what kind of value** to pass to the function?
```javascript
myFunction(lower("WHATEVER"))
// ^ When to evaluate this?
// What to give to the body of myFunction?
```
![](img/bean.gif) <!-- .element: class="stretch" -->
---
# Strict evaluation
*eager evaluation, greedy evaluation*
- **when:** as soon as possible
- **what kind of value:**
- *call by value*
- *call by reference*
- *call by sharing*
- ...
---
# Non-strict evaluation
*lazy evaluation*
- **call by name:** arguments are substituted directly into the function body
- **call by need:** same, with *memoization* (≈ *if* an argument is evaluated, its value is cached)
- ...
---
# Lazy evaluation
Delays the evaluation of an expression until its value is needed.
![](img/clean.gif) <!-- .element: class="stretch" -->
---
# What's the point?
- **optimization:** avoid useless computations
- **maintainability:**
- it is possible to express infinite data structures
- it is possible to define control structures as abstractions, instead of primitives
---
# Lo-Dash
> A JavaScript utility library delivering consistency, modularity, performance, & extras.
<https://lodash.com/>
- a JS library that allows to manipulate collections
- *lazy* since version 3
---
# Example
```javascript
var list = [0, 1, 2, 3, 4];
function addOne(nb) {
console.log(nb + ' + 1');
if (nb > 2) console.log('Slow');
return nb + 1;
}
function isSmall(nb) {
console.log(nb + ' smaller than 3?');
return nb < 3;
}
```
---
# Without Lo-Dash
```javascript
var result = list
.map(addOne)
.filter(isSmall)
.slice(0, 2);
```
```text
0 + 1
1 + 1
2 + 1
3 + 1
Slow
4 + 1
Slow
1 smaller than 3?
2 smaller than 3?
3 smaller than 3?
4 smaller than 3?
5 smaller than 3?
[ 1, 2 ]
```
<!-- .element: class="smallcode" -->
---
# With Lo-Dash
```javascript
var _ = require('lodash');
var result = _(list)
.map(addOne)
.filter(isSmall)
.take(2)
.value();
```
```text
0 + 1
1 smaller than 3?
1 + 1
2 smaller than 3?
[ 1, 2 ]
```
<!-- .element: class="smallcode" -->
---
# Without Lo-Dash
![](img/without-lodash.gif) <!-- .element: class="stretch" -->
---
# With Lo-Dash
![](img/with-lodash.gif) <!-- .element: class="stretch" -->
---
# Lazy evaluation
- separation of
- definition *→ how computations are defined?*
- execution *→ when values are computed?*
- *glue* that allows to assemble pieces of programs efficiently
**Pros:** can help us achieve better maintainability *and* performances
**Cons:** can introduce some *overhead* (depending on the technology)
---
# Concepts
- ~~referential transparency~~
- ~~higher-order functions~~
- ~~lazy evaluation~~
- immutability
---
# Immutability
> An immutable object is an object whose state cannot be modified after it is created.
![](img/good.gif) <!-- .element: class="stretch" -->
---
# Mutable in JS
- objects
- (which implies) arrays
```javascript
var object = {
a: 1,
b: 'BATMAN',
};
var alias = object;
object.a = 2;
object // { a: 2, b: 'BATMAN' }
alias // { a: 2, b: 'BATMAN' }
```
---
# const != immutable
```javascript
const object = {
a: 1,
b: 'BATMAN',
};
const alias = object;
object.a = 2;
object // { a: 2, b: 'BATMAN' }
alias // { a: 2, b: 'BATMAN' }
```
`const` prevent us from modifying **references**, not values!
*`const` is nice though ;)*
---
# Immutable.js
> Immutable persistent data collections for Javascript which increase efficiency and simplicity.
<https://facebook.github.io/immutable-js/>
- a library that gives us a API for immutable collections
- List, Stack, [Ordered]Map, [Ordered]Set, Record, ...
---
# Immutable.js
```javascript
const Immutable = require('immutable');
var map1 = Immutable.Map({a:1, b:2, c:3});
var map2 = map1.set('b', 50);
map1.get('b'); // 2
map2.get('b'); // 50
var map3 = map2.set('b', 2);
map1.equals(map3); // true
```
*Careful: do not confuse `Map` (data structure) and `map` (function)!*
---
# Pros
- readability/maintainability: 1 value per reference
- no side-effects
- *thread safe*
But what about performances?
![](img/suspicious.gif) <!-- .element: class="stretch" -->
---
# Performances
Introduces some *overhead*, but the balance maintainability vs. performance is often good.
![](img/tree.png) <!-- .element: class="stretch" -->
---
# Advice
## Use `const`
And use `let` when you cannot use `const`.
Do not use `var`.
## Avoid to create/use mutable API
A function that modifies an object should return a new object, not modify it secretly.
```javascript
const list = [1, 2, 3];
list.push(4);
// ^ side-effect
```
---
# Concepts
- ~~referential transparency~~
- ~~higher-order functions~~
- ~~lazy evaluation~~
- ~~immutability~~
---
# Going further
- [Why Functional Programming Matters](http://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf): why higher-order functions and lazy evaluation are great tools to write modular programs
- [JavaScript Alongé](https://leanpub.com/javascriptallongesix): a advanced book on JavaScript that explains some of the concepts we saw today
- [Is your programming language unreasonable?](http://fsharpforfunandprofit.com/posts/is-your-language-unreasonable/): why predictability of programming languages is important
---
# Questions?
![](img/question.gif) <!-- .element: class="stretch" -->
Twitter: [@d_sferruzza](https://twitter.com/d_sferruzza)
Slides are on GitHub:
[dsferruzza/conf-fp-is-not-just-lambdas](http://github.com/dsferruzza/conf-fp-is-not-just-lambdas)
</textarea>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script src="plugin/markdown/marked.js"></script>
<script>
function paragraphRenderer(text) {
var singleImage = text.match(/^(<img src=".+" alt=".*">)(\s*<!--.+-->)?$/);
if (singleImage !== null) {
var stretchComment = (typeof singleImage[2] === 'string') ? singleImage[2].match(/^\s*<!--\s*\.element:\s*(.*?)\s*(class\s*=\s*"stretch")\s*(.*?)\s*-->$/) : null;
if (stretchComment !== null && typeof stretchComment[2] === 'string') {
var comment = '<!-- .element: ' + ((typeof stretchComment[1] === 'string') ? stretchComment[1] : '') + ' ' + ((typeof stretchComment[3] === 'string') ? stretchComment[3] : '') + ' -->';
return '<figure class="stretch">' + singleImage[1] + comment + '</figure>';
}
else {
var comment = (typeof singleImage[2] === 'string') ? singleImage[2] : '';
return '<figure>' + singleImage[1] + comment + '</figure>';
}
}
else {
return '<p>' + text + '</p>\n';
}
}
var patchedRenderer = new marked.Renderer();
patchedRenderer.paragraph = paragraphRenderer;
Reveal.initialize({
controls: false,
slideNumber: true,
history: true,
transition: 'none',
dependencies: [
// { src: 'plugin/markdown/marked.js' }, // <-- useless because included before
{ src: 'plugin/markdown/markdown.js' },
{ src: 'plugin/notes/notes.js', async: true },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: 'plugin/zoom-js/zoom.js', async: true },
],
markdown: {
renderer: patchedRenderer,
},
});
</script>
</body>
</html>