-
Notifications
You must be signed in to change notification settings - Fork 4
/
partOne.html
1117 lines (929 loc) · 43.1 KB
/
partOne.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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=1024, user-scalable=no">
<title>Functional Programming</title>
<link rel="stylesheet" href="core/deck.core.css">
<link rel="stylesheet" href="extensions/goto/deck.goto.css">
<link rel="stylesheet" href="extensions/menu/deck.menu.css">
<link rel="stylesheet" href="extensions/navigation/deck.navigation.css">
<link rel="stylesheet" href="extensions/status/deck.status.css">
<link rel="stylesheet" href="extensions/hash/deck.hash.css">
<link rel="stylesheet" href="extensions/scale/deck.scale.css">
<link rel="stylesheet" href="extensions/codemirror/deck.codemirror.css">
<link rel="stylesheet" href="extensions/codemirror/themes/default.css">
<link rel="stylesheet" href="themes/style/swiss.css">
<style type="text/css">
.deck-container .slide code {
color: #c00; font-weight: bold;
}
.deck-container .slide h2 code {
color: #888;
}
</style>
<link rel="stylesheet" href="themes/transition/horizontal-slide.css">
<script src="modernizr.custom.js"></script>
</head>
<body class="deck-container">
<section class="slide">
<h1>Functional Programming</h1>
<h2>Scott Sauyet</h2>
</section>
<section class="slide">
<h2>An Overview of Functional Techniques<br/>
(for non FP'ers) using Javascript</h2>
<h3>Agenda</h3>
<ul>
<li>What is Functional Programming?</li>
<li>How Functional Programming Differs From Other Paradigms</li>
<li>Functional Programming in Javascript</li>
<li>Advantages and Disadvantages of Functional Style</li>
<li><del>Interaction of Functional and Object-Oriented Styles</del></li>
</ul>
</section>
<section class="slide">
<h2>What is Functional Programming?</h2>
<div class="slide">
<h3>No Single Definition</h3>
<p>There is no clear, widely-accepted definition of Functional Programming. It is a collection of
related features which cohere well into a very useful style of programming.</p>
<ul>
<li>Some of these features are readily available in Javascript.</li>
<li>Others can be used if care is taken.</li>
<li>And some are essentially impossible at the language level.</li>
</ul>
</div>
<p class="slide">But one of the main points of functional programming is that you can think of results you want,
not of the steps you need to take to get them.</p>
</section>
<section class="slide">
<h2>Chief difference between OOP and FP</h2>
<p>Reg Braithwaite has a <a href="http://raganwald.com/2013/04/08/functional-vs-OOP.html">good description</a>
of the central difference between these two paradigms. OO focuses on the <em>differences</em> in the data,
while FP concentrates on <em>consistent data structures</em>.</p>
<div class="slide">
<div style="float:left;width:45%;margin-right:3%;clear:both;">
<h3>Object-Oriented</h3>
<ul>
<li>Data and the operations upon it are tightly coupled</li>
<li>Objects hide their implementation of operations from other objects via their interfaces</li>
<li>The central model for abstraction is the data itself</li>
<li>The central activity is composing new objects and extending existing objects by adding new methods
to them</li>
</ul>
</div>
<div class="slide" style="float:left;width:45%;margin-right:3%;">
<h3>Functional</h3>
<ul>
<li>Data is only loosely coupled to functions</li>
<li>Functions hide their implementation, and the language’s abstractions speak to functions and the way
they are combined or expressed</li>
<li>The central model for abstraction is the function, not the data structure.</li>
<li>The central activity is writing new functions</li>
</ul>
</div>
</div>
</section>
<section class="slide">
<h2>What does this mean in the business environment?</h2>
<p>Is one of these techniques the clear-cut winner in the business world? Is it functional or object-oriented?</p>
<div class="slide">
<h3>Are you sure?</h3>
</div>
<div class="slide">
<br/>
<h3>How much business logic is written like this?</h3>
<div>
<div class="code" mode="plsql" style="display: none;">SELECT orders.order_id, orders.order_date, suppliers.supplier_name
FROM suppliers
RIGHT OUTER JOIN orders
ON suppliers.supplier_id = orders.supplier_id
WHERE orders.order_status = 'INCOMPLETE'
ORDER BY orders.order_date DESC;</div>
</div>
<div class="slide">
<br/>
<p>SQL is very similar to functional languages, and it permeates business. It uses a consistent data structure
(tables with records organized into columns) and a few basic functions that can be combined into
arbitrary queries. And it shares one other important feature with functional languages: it is
<strong>declarative</strong>.</p>
</div>
</div>
</section>
<section class="slide">
<h2>Declarative vs Imperative Programming</h2>
<p>One main distinguishing characteristics of functional programming languages is that they describe <em>what</em>
they want done, and not <em>how</em> to do it. OO, inside its methods, still uses mostly imperative techniques.</p>
<!--div>
<div class="code" mode="javascript" style="display: none;">var square = function(x) {return x * x};</div>
</div-->
<div class="slide">
<h3>Imperative style</h3>
<div>
<textarea class="code" mode="javascript" style="display: none;" runnable="true">var sumOfSquares = function(list) {
var result = 0;
for (var i = 0; i < list.length; i++) {
result += square(list[i]);
}
return result;
};
console.log(sumOfSquares([2, 3, 5]));</textarea>
</div>
</div>
<div class="slide">
<h3>Functional style</h3>
<div>
<textarea class="code" mode="javascript" style="display: none;" runnable="true">var sumOfSquares = pipe(map(square), reduce(add, 0));
console.log(sumOfSquares([2, 3, 5]));</textarea>
</div>
<br/>
<br/>
</div>
</section>
<section class="slide">
<h2>Functional Programming in Javascript</h2>
<p>With first-class function, closures, and anonymous functions, Javascript allows us to do a great deal of
functional programming, even if we don't have things like pattern matching and homoiconicity. There are
some tools built in to modern Javascript environments, and it's straightforward to roll your own.</p>
<p>For the remainder of this talk, we will use the <a href="https://github.com/ramda/ramda">Ramda</a> library that
<a href="https://github.com/buzzdecafe">Michael Hurley</a> and I have been developing. But there are a number
of interesting alternatives available:</p>
<ul>
<li class="slide"><a href="https://github.com/raganwald/allong.es">allong.es</a> is a fairly new functional
combinators and decorators library</li>
<li class="slide"><a href="https://github.com/fogus/lemonad">Lemonad</a> is a general-purpose functional
programming library</li>
<li class="slide"><a href="https://github.com/dtao/lazy.js">Lazy</a> and
<a href="https://github.com/goatslacker/lz">Lz</a> are libraries for lazy list processing</li>
<li class="slide"><a href="http://underscorejs.org/">Underscore</a> and its more performant clone,
<a href="http://lodash.com/">Lo-Dash</a>, are general utility libraries with a number of functional
capabilities</li>
<li class="slide"><a href="http://osteele.com/sources/javascript/functional/">Functional Javascript</a>,
although perhaps outdated today, was the very first successful functional programming library for
Javascript</li>
</ul>
</section>
<section class="slide">
<h2>Using Functional Techniques in Javacript</h2>
<p>We will approach functional programming by converting an imperative example into a functional one.</p>
<p>We will also briefly examine an object-oriented approach, but we'll see that the code that we would like
to address is very similar to the imperative one, just organized differently.</p>
<p>Our example will be a Task List application, fetching something like the following data from the server:</p>
<div><textarea class="code" mode="javascript" style="display: none;">var data = {
result: "SUCCESS",
interfaceVersion: "1.0.3",
requested: "10/17/2013 15:31:20".
lastUpdated: "10/16/2013 10:52:39",
tasks: [
{id: 104, complete: false, priority: "high", dueDate: "11/29/2013",
member: "Scott", title: "Do something", created: "9/22/2013"},
{id: 105, complete: false, priority: "medium", dueDate: "11/22/2013",
member: "Lena", title: "Do something else", created: "9/22/2013"},
{id: 107, complete: true, priority: "high", dueDate: "11/22/2013",
member: "Mike", title: "Fix the foo", created: "9/22/2013"},
{id: 108, complete: false, priority: "low", dueDate: "11/15/2013",
member: "Punam", title: "Adjust the bar", created: "9/25/2013"},
{id: 110, complete: false, priority: "medium", dueDate: "11/15/2013",
member: "Scott", title: "Rename everything", created: "10/2/2013"},
{id: 112, complete: true, priority: "high", dueDate: "11/27/2013",
member: "Lena", title: "Alter all quuxes", created: "10/5/2013"}
// , ...
]
};</textarea></div>
<br/>
</section>
<section class="slide">
<h2>Our Goal</h2>
<div><textarea class="code" mode="javascript" style="display: none;">tasks: [
{id: 104, complete: false, priority: "high", dueDate: "11/29/2013",
member: "Scott", title: "Do something", created: "9/22/2013"},
{id: 105, complete: false, priority: "medium", dueDate: "11/22/2013",
member: "Lena", title: "Do something else", created: "9/22/2013"},
// , ...
]</textarea></div>
<br/>
<p>The goal will be a function that accepts a `member` parameter, then fetches the data from the server (or from
some application cache), chooses the tasks for that member that are not complete, returns their ids, priorities,
titles, and dues dates, sorted by due date.</p>
<p>Since the fetch from the server will likely be asynchronous, we'll hook everything together with promises, and
our function will return a promise that should resolve to an array of objects with the required properties.</p>
<p>For our illustrative purposes, we will ignore all error-checking concerns. Obviously in a production system,
we would need to consider server-side failures, and bad data scenarios.</p>
</section>
<section class="slide">
<h2>Sample Imperative Approach</h2>
<div><textarea class="code" mode="javascript" style="display: none;">var getIncompleteTaskSummariesForMember_imperative = function(memberName) {
return fetchData()
.then(function(data) {
return data.tasks;
})
.then(function(tasks) {
var results = [];
for (var i = 0, len = tasks.length; i < len; i++) {
if (tasks[i].member == memberName) {
results.push(tasks[i]);
}
}
return results;
})
.then(function(tasks) {
var results = [];
for (var i = 0, len = tasks.length; i < len; i++) {
if (!tasks[i].complete) {
results.push(tasks[i]);
}
}
return results;
})</textarea></div>
<br/>
<p>(continued on the next slide.)</p>
</section>
<section class="slide">
<h2>Sample Imperative Approach (continued)</h2>
<div><textarea class="code" mode="javascript" style="display: none;">
.then(function(tasks) {
var results = [], task;
for (var i = 0, len = tasks.length; i < len; i++) {
task = tasks[i];
results.push({
id: task.id,
dueDate: task.dueDate,
title: task.title,
priority: task.priority
});
}
return results;
})
.then(function(tasks) {
tasks.sort(function(first, second) {
return first.dueDate - second.dueDate;
});
return tasks;
});
};</textarea></div>
</section>
<section class="slide">
<h2>Similar Object-Oriented Approach</h2>
<div><textarea class="code" mode="javascript" style="display: none;"> // main method
var getIncompleteTaskSummariesForMember_objectOriented = function(memberName) {
return fetchData()
.then(function(data) {
var taskList = new TaskList(data.tasks);
taskList.chooseByMember(memberName);
taskList.chooseByCompletion(false);
var newTaskList = taskList.getSummaries();
newTaskList.sort(new TaskListSorter("dueDate"));
return newTaskList.tasks;
});
};</textarea></div>
<br/>
<p>(continued on the next slide.)</p>
</section>
<section class="slide">
<h2>Object-Oriented Approach (continued)</h2>
<div><textarea class="code" mode="javascript" style="display: none;">var TaskList = (function() {
var TaskList = function(/*Task[]*/ tasks) {
this.tasks = tasks;
};
TaskList.prototype.chooseByMember = function(memberName) {
var results = [];
for (var i = 0, len = this.tasks.length; i < len; i++) {
if (this.tasks[i].member === memberName) {
results.push(this.tasks[i]);
}
}
this.tasks = results;
};
TaskList.prototype.chooseByCompletion = function(completion) {
var results = [];
for (var i = 0, len = this.tasks.length; i < len; i++) {
if (this.tasks[i].complete == completion) {
results.push(this.tasks[i]);
}
}
this.tasks = results;
};</textarea></div>
</section>
<section class="slide">
<h2>Object-Oriented Approach (continued)</h2>
<div><textarea class="code" mode="javascript" style="display: none;">TaskList.prototype.getSummaries = function() {
var results = [], task;
for (var i = 0, len = this.tasks.length; i < len; i++) {
task = this.tasks[i];
results.push({
id: task.id,
dueDate: task.dueDate,
title: task.title,
priority: task.priority
});
}
return new TaskList(results);
};
TaskList.prototype.sort = function(/*TaskListSorter*/ sorter) {
this.tasks.sort(sorter.getSortFunction());
};
return TaskList;
}());</textarea></div>
<br/>
<p>(continued on the next slide.)</p>
</section>
<section class="slide">
<h2>Object-Oriented Approach (continued)</h2>
<div><textarea class="code" mode="javascript" style="display: none;">var TaskListSorter = (function() {
var TaskListSorter = function(propName) {
this.propName = propName;
};
TaskListSorter.prototype.getSortFunction = function() {
var propName = this.propName;
return function(first, second) {
return first[propName] < second[propName] ? -1 :
first[propName] > second[propName] ? +1 : 0;
};
};
return TaskListSorter;
}());</textarea></div>
<br/>
<p>We could continue by defining <code>Task</code> and <code>MinimalTask</code>, but that's probably overkill in
Javascript.</p>
<p class="slide">It's important for our point to note that the difference between the plain imperative code and the
Object-Oriented code, outside a number of `<code>this</code>` keywords, is mostly just organization. The
contents of the functions are much the same; it's the way they are organized that varies.</p>
<p class="slide">This means that for our purposes, we can focus on the slightly simpler imperative code.</p>
</section>
<section class="slide">
<h2>Converting to Functional Code</h2>
<p>The process for the remainder of this talk will be to convert this code into concise, readable, functional
code, one block at a time, explaining some of the basic building blocks of functional programming as we go.
First up is this little function:</p>
<div><textarea class="code" mode="javascript" style="display: none;">.then(function(data) {
return data.tasks;
})</textarea></div>
<br/>
<div class="slide">
<h3>Functional Version</h3>
<div><textarea class="code" mode="javascript" style="display: none;">.then(get('tasks'))</textarea></div>
</div>
<div class="slide">
<br/>
<p>So the obvious question, then, is, what is the <code>get</code> function?</p>
</div>
</section>
<section class="slide">
<h2>The <code>get</code> Function</h2>
<p>This is the definition of the <code>get</code> function in the Ramda library:</p>
<div><textarea class="code" mode="javascript" style="display: none;">var get = curry(function(prop, obj) {return obj[prop];});</textarea></div>
<br/>
<div class="slide">
<p>Ignoring the <code>curry</code> wrapper, this is pretty simple. <code>get</code> (which also goes by the
alias of <code>prop</code>) is a function which accepts a property name and an object, and returns the
property of the object with that name.</p>
</div>
<div class="slide">
<br/>
<p>Our <code>then</code> call needs a function, so <code>curry</code> must be doing something interesting with
this function, which should return an object propery, so that it insteads returns a new function. We need
to take a detour to discuss <code>curry</code> a bit.</p>
</div>
</section>
<section class="slide">
<h2>Curry</h2>
<img src="img/curry.png"/>
<div class="slide">
<br/>
<h3>Very sorry, no delicious spicy food here.</h3>
</div>
</section>
<section class="slide">
<h2>Currying Functions</h2>
<p>Currying is the process of converting functions that take multiple arguments into ones that, when supplied
fewer arguments, return new functions that accept the remaining ones.</p>
<div class="slide">
<div><textarea class="code" mode="javascript" style="display: none;" runnable="true">var add = curry(function(a, b) {return a + b;});
var add42 = add(42);
console.log(add42(10)); //=> 52
console.log(add42(7)); // 49</textarea></div>
</div>
</section>
<section class="slide">
<h2>Back to <code>get</code></h2>
<p>Remember the definition of <code>get</code>:</p>
<div><textarea class="code" mode="javascript" style="display: none;">var get = curry(function(prop, obj) {return obj[prop];});</textarea></div>
<div class="slide">
<br/>
<p>Now that we understand <code>curry</code>, we can see that a manually curried version of this function might
look like this:</p>
<div><textarea class="code" mode="javascript" style="display: none;">var get = function(prop) {
return function(obj) {
return obj[prop];
};
};</textarea></div>
</div>
<div class="slide">
<br/>
<p>And that means that our new <code>get('tasks')</code> is equivalent to</p>
<div><textarea class="code" mode="javascript" style="display: none;">function(obj) {
return obj['tasks'];
}</textarea></div>
</div>
</section>
<section class="slide">
<h2>Filtering</h2>
<p>So far, we've been able to replace this block:</p>
<div><textarea class="code" mode="javascript" style="display: none;">.then(function(data) {
return data.tasks;
})</textarea></div>
<br/>
<p>with this one:</p>
<div><textarea class="code" mode="javascript" style="display: none;">.then(get('tasks'))</textarea></div>
<div class="slide">
<br/>
<p>The next block to replace looks like this:</p>
<div><textarea class="code" mode="javascript" style="display: none;">.then(function(tasks) {
var results = [];
for (var i = 0, len = tasks.length; i < len; i++) {
if (tasks[i].member == memberName) {
results.push(tasks[i]);
}
}
return results;
})</textarea></div>
</div>
<div class="slide">
<br/>
<p>What we're doing is running a filter on the input list, keeping only those that have the correct
<code>member</code> property. Let's see how we would do this in a functional paradigm.</p>
</div>
</section>
<section class="slide">
<h2>Functional Filtering</h2>
<p>Many functional libraries come with a <code>filter</code> function, which accepts a predicate function and
a list, and returns a new list consisting of those elements of the original list for which the predicate
function returns <code>true</code>.</p>
<p>Ramda has one, called <code>filter</code>, and like pretty much every function of more than one parameter, it's
curried, with the signature, <code>filter(predicate, list)</code>.</p>
<p>Remembering that the <code>then</code> block will pass the list of tasks to us, we really want to call filter
with a predicate, getting back a curried function that will accept a list.</p>
<div class = slide>
<p>Here's a first pass:</p>
<div><textarea class="code" mode="javascript" style="display: none;">.then(filter(function(task) {
return task.member == memberName;
}))</textarea></div>
<br/>
<p>(Remember that <code>memberName</code> was a parameter to our original function.)</p>
</div>
</section>
<section class="slide">
<h2>Focused Code</h2>
<p>So, for one thing, we've reduced the weight of our custom code:</p>
<div class="slide">
<h3>Original code</h3>
<div><textarea class="code" mode="javascript" style="display: none;">.then(function(tasks) {
var results = [];
for (var i = 0, len = tasks.length; i < len; i++) {
if (tasks[i].member == memberName) {
results.push(tasks[i]);
}
}
return results;
})</textarea></div>
</div>
<div class="slide">
<br/>
<h3>Functional version</h3>
<div><textarea class="code" mode="javascript" style="display: none;">.then(filter(function(task) {
return task.member == memberName;
}))</textarea></div>
</div>
<div class="slide">
<br/>
<p>But we've done something more important too: We've moved the focus from iteration and updating the state
of a local collection to the real point of this block: choosing the tasks with the proper
<code>member</code> property.</p>
<p>One of the most important features of functional programming is that it makes it easy to shift focus in
this manner.</p>
</div>
</section>
<section class="slide">
<h2>Rejecting elements</h2>
<p>The next block is similar, except that instead of using <code>filter</code>, we will use <code>reject</code>,
which behaves exactly the same except that it chooses those members of the list that <strong>don't</strong>
match the predicate. We replace this code:</p>
<div><textarea class="code" mode="javascript" style="display: none;">.then(function(tasks) {
var results = [];
for (var i = 0, len = tasks.length; i < len; i++) {
if (!tasks[i].complete) {
results.push(tasks[i]);
}
}
return results;
})</textarea></div>
<br/>
<p>with this:</p>
<div><textarea class="code" mode="javascript" style="display: none;">.then(reject(function(task) {
return task.complete === true;
)))</textarea></div>
</section>
<section class="slide">
<h2>Refactoring... already</h2>
<p>A reasonable question would be why we didn't do this instead, which would work equally well:</p>
<div><textarea class="code" mode="javascript" style="display: none;">.then(filter(function(task) {
return task.complete !== true;
))</textarea></div>
<div class="slide">
<br/>
<p>The reason is that the similarity between these two blocks will offer us a chance to refactor our code
into something still more descriptive:</p>
<div><textarea class="code" mode="javascript" style="display: none;">function(task) {
return task.member == memberName;
}</textarea></div>
<br/>
<div><textarea class="code" mode="javascript" style="display: none;">function(task) {
return task.complete === true;
)</textarea></div>
</div>
<div class="slide">
<p>Both of these functions accept an object and return a boolean that describes whether a particular
property of the object has a given value. Perhaps a good name for a function that generates such
functions would be <code>propMatches</code>. Let's implement that.</p>
</div>
</section>
<section class="slide">
<h2>Implementing <code>propMatches</code></h2>
<h3>Simplest Approach</h3>
<div><textarea class="code" mode="javascript" style="display: none;">var propMatches = function(prop, val) {
return function(obj) {
return obj[prop] === val;
};
};
// ...
.then(reject(propMatches("complete", true)));</textarea></div>
<div class="slide">
<br/>
<p>This works, and we could leave it there, but we're going to take another detour into a popular style of
functional programming known as <code>points-free</code> coding.</p>
</div>
<div class="slide">
<p>The name has nothing to do with <code>'.'</code> characters. It derives from mathematics and has something
to do with homomorphisms on topological spaces.</p>
</div>
<div class="slide">
<p>This won't be on the test.</p>
</div>
</section>
<section class="slide">
<h2>Points-free definitions</h2>
<p>With the functions <code>add</code> (which adds two numbers) and <code>reduce</code> (which runs the supplied
function against an accumulator and each element of the list, feeding the result of each call into the next one
and returning the final result), we can easily define a <code>sum</code> function like this:</p>
<div><textarea class="code" mode="javascript" style="display: none;">var sum = function(list) {
return reduce(add, 0, list);
};</textarea></div>
<br/>
<div class="slide">
<br/>
<p>Because of the automatic currying, though, the following is entirely equivalent:</p>
<div><textarea class="code" mode="javascript" style="display: none;">var sum = reduce(add, 0);</textarea></div>
</div>
<div class="slide">
<br/>
<p>This is the points-free style, defining functions without ever making direct reference to their
arguments.</p>
</div>
<div class="slide">
<p>There are plenty of <del>arguments in favor of it</del>, plenty of <del>points to support it</del>,
reasons to like it, but the most important one might just be the simplicity. There is a great deal to be
said for elegant, readable code.</p>
</div>
</section>
<section class="slide">
<h2>A points-free version of <code>propMatches</code></h2>
<p>Can we redefine the following in a points-free style?</p>
<div><textarea class="code" mode="javascript" style="display: none;">var propMatches = function(prop, val) {
return function(obj) {
return obj[prop] === val;
};
}</textarea></div>
<div class="slide">
<br/>
<p>Here's a version that is closer to points-free:</p>
<div><textarea class="code" mode="javascript" style="display: none;">var propMatches = function(prop, val) {
return compose(eq(val), get(prop));
}</textarea></div>
<div class="slide">
<br/>
<p>Huh? What? <code>compose</code>? <code>eq</code>?</p>
</div>
<div class="slide">
<code>eq</code> is easy: like all good functions of multiple parameters, it's curried, and it simply reports
whether its two arguments are equal. So <code>eq(val)</code> is a function which reports whether its
parameter has the same value as does <code>val</code>. But now we need to discuss <code>compose</code>.
</div>
</div>
</section>
<section class="slide">
<h2>Functional composition</h2>
<p>I have <a href="http://scott.sauyet.com/Javascript/Talk/Compose/">another short talk</a> dedicated entirely to
techniques of functional composition. This is a very brief overview:</p>
<p>In mathematics <code>f ∘ g</code> (pronounced "f composed with g") is the function that given <code>x</code>,
returns <code>f(g(x))</code>.</p>
<p>So if we follow the mathematical model <code>compose(add1, square)(x)</code> should equal <code>add1(square(x))</code>.</p>
<br/>
<div class="slide">
<h3>Simplest Implementation</h3>
<div><textarea class="code" mode="javascript" style="display: none;">var compose = function(f, g) {
return function(x) {
return f(g(x));
};
};</textarea></div>
<br/>
<p>Ramda also defines <code>pipe</code>, which does much the same thing, but runs the functions
in the opposite order. So <code>pipe(add1, square)(x)</code> equals <code>square(add1(x))</code>. Both
styles have their uses.</p>
</div>
</section>
<section class="slide">
<h2>Back to <code>propMatches</code></h2>
<p>So now this definition makes sense:</p>
<div><textarea class="code" mode="javascript" style="display: none;">var propMatches = function(prop, val) {
return pipe(get(prop), eq(val));
}</textarea></div>
<br/>
<div class="slide">
<p>Switching from <code>compose</code> to <code>pipe</code> gives us a further way to clean it up, and make it entirely points-free, using a useful feature of Ramda we
haven't seen implemented in other libraries, which we call (for now) <code>use-over</code>. Used like
<code>use(func).over(transformer1, ... transformerN)</code>, this returns a function which accepts N parameters,
feeds them to the respective transformers, and then calls <code>func</code> using the results of all these.
This gives us the final version of propMatches:</p>
</div>
<div class="slide">
<div><textarea class="code" mode="javascript" style="display: none;">var propMatches = use(pipe).over(get, eq);</textarea></div>
</div>
</section>
<section class="slide">
<h2>Using our new function</h2>
<p>This function seems quite useful, and we might want to fold it into Ramda one day, but it's not there now. Still,
all these explanations aside, it was only a minute or two of work to do this refactoring and arrive at a
fairly simple version of <code>propMatches</code>. We would plug it back in like this:</p>
<div><textarea class="code" mode="javascript" style="display: none;">var propMatches = use(pipe).over(get, eq);
// ...
.then(filter(propMatches('member', memberName)))
.then(reject(propMatches('complete', true)))</textarea></div>
</section>
<section class="slide">
<h2>New objects from old</h2>
<p>The next block we wanted to update looked like this:</p>
<div><textarea class="code" mode="javascript" style="display: none;">.then(function(tasks) {
var results = [], task;
for (var i = 0, len = tasks.length; i < len; i++) {
task = tasks[i];
results.push({
id: task.id,
dueDate: task.dueDate,
title: task.title,
priority: task.priority
})
}
return results;
})</textarea></div>
<div class="slide">
<br/>
<h3>Functional version:</h3>
<div><textarea class="code" mode="javascript" style="display: none;">.then(map(pick(['id', 'dueDate', 'title', 'priority'])))</textarea></div>
<br/>
<p>You're a smart bunch, right? I probably don't even have to explain what <code>pick</code> does, right?</p>
</div>
<div class="slide">
<p>Good, then we can move on to discuss <code>map</code>.</p>
</div>
</section>
<section class="slide">
<h2>The <code>map</code> function</h2>
<p><em>It is not down in any map; true places never are. – Herman Melville</em></p>
<br/>
<p>One of the most fundamental functions used in FP is <code>map</code>, which is used to convert one list into
a related one by running the same function against each member.</p>
<div class="slide">
<div><textarea class="code" mode="javascript" style="display: none;" runnable="true">var fiveSquares = map(square, [1, 2, 3, 4, 5]); // => [1, 4, 9, 16, 25];
var shouts = map(toUpperCase, ["oy", "vey"]); //=> ["OY", "VEY"]</textarea></div>
</div>
<div class="slide">
<br/>
<p>There isn't much more to say about <code>map</code>, but it's important to point out that this function
and <code>reduce</code>, which we mentioned briefly earlier, are among the most important functional
programming tools around.</p>
</div>
</section>
<section class="slide">
<h2>Partial clones of our objects.</h2>
<p>We used <code>map</code> like this:</p>
<div><textarea class="code" mode="javascript" style="display: none;">.then(map(pick(['id', 'dueDate', 'title', 'priority'])))</textarea></div>
<br/>
<p>The magic of currying is again at work here:</p>
<ul>
<li class="slide"><code>pick</code> accepts a list of properties and an object and return a partial clone, copying those
properties from the original. Since we just pass in the properties, this curried function returns a
new function that accepts an object and returns that partial clone.</li>
<li class="slide"><code>map</code> accepts a function and a list an applies the function to the list. But because it's
curried, and because we supply only the function generated by the curried <code>pick</code>, this one
also returns a new function which will accept a list and create these partial clones of each element in
the list.</li>
<li class="slide">This function is passed to <code>then</code>, which will simply pass along its parameter (whenever that
becomes ready) to our function and "return" the result of running our function against it. (We simply
know because of the way prior calls have been built that this will be a list of tasks.)</li>
</ul>
</section>
<section class="slide">
<h2>A final task of some <code>sort</code></h2>
<p>The last segment we wanted to convert looked like this:</p>
<div><textarea class="code" mode="javascript" style="display: none;">.then(function(tasks) {
tasks.sort(function(first, second) {
return first.dueDate - second.dueDate;
});
return tasks;
});</textarea></div>
<div class="slide">
<br/>
<p>We won't discuss the implementation of <code>sortBy</code>, but the basic idea is that it returns a new list
made from an old one by sorting the elements according to keys generated by the function passed to it. For
instance:</p>
<div><textarea class="code" mode="javascript" style="display: none;">sortBy(function(person) {
return person.lastName + "," + person.firstName;
}, people);</textarea></div>
</div>
</section>
<section class="slide">
<h2>Again with the <code>curry</code></h2>
<p>Again, we take advantage of the fact that our important functions are curried, and use
<code>get('dueDate')</code>. This creates a function that, fed one of our task objects, returns its due date.
We can feed this into <code>sortBy</code> to get the following:</p>
<div><textarea class="code" mode="javascript" style="display: none;">.then(sortBy(get('dueDate')))</textarea></div>
<div class="slide">
<br/>
<p>While this is not a <strong>lot</strong> less code than the original:</p>
<div><textarea class="code" mode="javascript" style="display: none;">.then(function(tasks) {
tasks.sort(function(first, second) {
return first.dueDate - second.dueDate;
});
return tasks;
});</textarea></div>
<br/>
<p>it clearly is a savings. However, much more importantly, the code is all clearly aimed at our problem. The
new code is much closer to a direct translation of the English specifications than is the original.</p>
</div>
</section>
<section class="slide">
<h2>Recap – Imperative</h2>
<div><textarea class="code" mode="javascript" style="display: none;">var getIncompleteTaskSummariesForMember_imperative = function(memberName) {
return fetchData()
.then(function(data) {
return data.tasks;
})
.then(function(tasks) {
var results = [];
for (var i = 0, len = tasks.length; i < len; i++) {
if (tasks[i].member == memberName) {
results.push(tasks[i]);
}
}
return results;
})
.then(function(tasks) {
var results = [];
for (var i = 0, len = tasks.length; i < len; i++) {
if (!tasks[i].complete) {
results.push(tasks[i]);
}
}
return results;
})
.then(function(tasks) {
var results = [], task;
for (var i = 0, len = tasks.length; i < len; i++) {
task = tasks[i];
results.push({
id: task.id,
dueDate: task.dueDate,
title: task.title,
priority: task.priority
})
}
return results;
})
.then(function(tasks) {
tasks.sort(function(first, second) {
return first.dueDate - second.dueDate;
});
return tasks;
});</textarea></div>
</section>
<section class="slide">
<h2>Recap – Functional</h2>
<div><textarea class="code" mode="javascript" style="display: none;">var propMatches = use(pipe).over(get, eq); // TODO: move to library?
var getIncompleteTaskSummariesForMember_functional = function(memberName) {
return fetchData()
.then(get('tasks'))
.then(filter(propMatches('member', memberName)))
.then(reject(propMatches('complete', true)))
.then(map(pick(['id', 'dueDate', 'title', 'priority'])))
.then(sortBy(get('dueDate')));
};
</textarea></div>
</section>
<section class="slide">