-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.html
1356 lines (1127 loc) · 52.7 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
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>Interaction of Functional and Object-Oriented Styles</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>
</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 Features in Javascript</h2>
<h3>Easily available in Javascript</h3>
<ul>
<li class="slide">First-class functions</li>
<li class="slide">Lambdas/Anonymous Functions with closures</li>
<li class="slide">Compact, even terse, functions</li>
</ul>
<h3 class="slide">Possible to accomplish in Javascript with some care</h3>
<ul>
<li class="slide">Mostly stateless processing</li>
<li class="slide">Side-effect-free function calls</li>
</ul>
</section>
<section class="slide">
<h2>Not available in current versions Javascript</h2>
<ul>
<li class="slide">Performant recursion through tail call optimization</li>
<li class="slide">Pattern matching (Haskell, Erlang)</li>
<li class="slide">Lazy Evaluation (Miranda, Haskell)</li>
<li class="slide">Homoiconicity (mostly LISP-like languages?)</li>
</ul>
<div class="slide">
<hr/>
<p>We will take a look a brief look at these functional programming features of other languages first, then turn
our focus to those things we can actually accomplish in Javascript.</p>
</div>
</section>
<section class="slide">
<h2>Shared Example</h2>
<p>Following an example from <a href="http://paulbarry.com/articles/2009/08/30/tail-call-optimization">Paul Barry</a>
we will use the example of the chances of winning a lottery. This calculates the odds of choosing the correct
`n` numbers out of the `p` possibilities.</p>
<p>Here is an iterative version of the code:</p>
<div>
<textarea class="code" mode="javascript" style="display: none;" runnable="false">function odds(n, p) {
var acc = 1;
for(var i = 0; i < n; i++) {
acc *= (n - i) / (p - i);
}
return acc;
}
console.log(odds(3, 10)); //=> (3/10) * (2/9) * (1/8) => (1/120) => 0.008333...</textarea>
</div>
<br/>
</section>
<section class="slide">
<h2>Recursive Version</h2>
<p>This is similar, but written recursively:</p>
<div><textarea class="code" mode="javascript" style="display: none;" runnable="false">// Recursive version
function odds(n, p) {
return (n == 0) ? 1 : (n / p) * odds(n - 1, p - 1);
}
console.log(odds(3, 10)); //=> (3/10) * (2/9) * (1/8) => (1/120) => 0.008333...</textarea></div>
<div class="slide">
<br/>
<p>There are many reasons that functional programmers prefer recursion, but one very simple one is that
recursive functions are often much more elegant than their iterative cousins. It's easier to reason
about them.</p>
</div>
<div class="slide">
<p>Unfortunately, they often don't perform as well. All the overhead of creating stack contexts for
function calls tends to add up. But certain kinds of recursive calls <em>can</em> be easily optimized.</p>
</div>
</section>
<section class="slide">
<h2>This code in tail-call formulation:</h2>
<div><textarea class="code" mode="javascript" style="display: none;" runnable="false">var odds = (function(){
var odds1 = function(n, p, acc) {
return (n == 0) ? acc : odds1(n - 1, p - 1, (n / p) * acc);
};
return function(n, p) {
return odds1(n, p, 1);
}
})();</textarea></div>
<div class="slide">
<br/>
<p>Note that the recursive call in <code>odds1</code> is the last statement in its branch of the function.
If this is true for all recursive calls, then the function is <code>tail-recursive</code>, and the
compiler can replace the entire set of nested calls with simple <code>JUMP</code> operations.</p>
</div>
<div class="slide">
<p>Such optimizations are required by many functional languages.</p>
</div>
<div class="slide">
<p>This is slated to become required in the next version of the specification for Javascript, but it won't
be consistently available client-side for some time.</p>
</div>
</section>
<section class="slide">
<h2>Pattern Matching</h2>
<p>Some languages make use of an interesting technique to define functions: pattern matching. Rather than use
<code>if-blocks</code> in the body of the function, parameter-matching is used to choose which of a collection
of related functions should be called. Here we can see it in Erlang.</p>
<div class="slide">
<h3>Simple recursive version</h3>
<div><textarea class="code" mode="erlang" style="display: none;">odds(0, _) -> 1;
odds(N, P) -> (N / P) * odds(N - 1, P - 1).</textarea></div>
</div>
<div class="slide">
<br/>
<h3>Tail-call version</h3>
<div><textarea class="code" mode="erlang" style="display: none;">-export([odds/2]).
odds(N, P) -> odds(N, P, 1).
odds(0, _, Acc) -> Acc;
odds(N, P, Acc) -> odds(N - 1, P - 1, (N / P) * Acc).</textarea></div>
</div>
</section>
<section class="slide">
<h2>Lazy Evaluation</h2>
<p>Many of us are most familiar with languages that evaluate their expressions as soon as they're encountered. But
there are some that wait until the last possible instant. This can have some real benefits.</p>
<div class="slide">
<p>We'll switch examples here, as there's not much call to do lazy evaluation for lottery odds. We will follow a
<a href="http://stackoverflow.com/a/284180/1243641">Haskell example</a> from Chris Eidhof</p>
<div><textarea class="code" mode="haskell" style="display: none;">quickSort [] = []
quickSort (x:xs) = quickSort (filter (< x) xs)
++ [x]
++ quickSort (filter (>= x) xs)
minimum ls = head (quickSort ls)</textarea></div>
<br/>
<p>Note that the right half of quicksort is not calculated in finding the minimum. (Also note the pattern matching here too!)</p>
</div>
<p class="slide">One <a href="http://stackoverflow.com/a/2165370/1243641">very interesting comparison</a> is that
lazy evaluation is to the CPU what garbage collection is to memory. The garbage collector allows you to pretend
that you have infinite memory; lazy evaluation allows you to pretend that you have infinite processing power.</p>
<p class="slide">But there are many reasons to like lazy evaluation. It allows you to operate on theoretically
infinite data structures, calculating only those parts you need. And it allows you to define your own
efficient control structures inside the language instead of only at the level of the language syntax.</p>
<br/>
</section>
<section class="slide">
<h2>Homoiconicity</h2>
<div class="slide">
<p>No groaning. At one time you had to learn what <em>polymorphism</em> meant, too!</p>
</div>
<div class="slide">
<h3><em>homoiconicity</em></h3>
<ul>
<li><em>homo</em>: from the Greek <em>homo</em>, same</li>
<li><em>icon</em>: from the Greek <em>eikon</em>, likeness, image, portrait</li>
<li><em>icity</em>: from the Greek <em>icit</em>, extra letters to make words more pretentious</li>
</ul>
</div>
</section>
<section class="slide">
<h2>Homoiconicity in LISP-like languages</h2>
<p>Homoiconicity has to do with the fact that in some languages, programs are written in a format easily
interpreted also as a data structure. In Scheme, the following is just a quoted list of three items,
<code>define</code>, <code>(square x)</code> (itself a list), and <code>(* x x)</code> (another list)</p>
<div>
<div class="code" mode="scheme" style="display: none;">'(define (square x) (* x x))</div>
</div>
<div class="slide">
<br/>
<p>But the following, which looks almost identical, is a function definition:</p>
<div>
<div class="code" mode="scheme" style="display: none;">(define (square x) (* x x))</div>
</div>
</div>
<div class="slide">
<br/>
<p>LISP-like languages can use this feature to build very powerful domain-specific languages. Many would
claim that this is the key feature that has allowed LISP to become the oldest language still in widespread
use.</p>
</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, to instead returning a new function. So 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>Currying multiple arguments</h2>
<p>Different versions of currying work slightly differently. In Ramda, you can pass any of the arguments at any
time to a curried function. If the total arguments passed have not yet reached the required number, then
you will get back a new function. If you reach (or exceed) that number, you will get back the final result.</p>
<div><textarea class="code" mode="javascript" style="display: none;" runnable="true">var formatName = curry(function(first, middle, last) {
return first + " " + middle + " " + last;
});
var f = formatName("James"); // returns a function
var g = f("Earl"); // returns a function
g("Jones"); //=> "James Earl Jones"
var h = formatName("James", "Earl"); // returns a function
h("Jones"); //=> "James Earl Jones"
// Note that g and h are equivalent functions
formatName("James", "Earl", "Jones"); //=> "James Earl Jones"</textarea></div>
<div>
<br/>
<p>Some insist that this is not truly currying, but should be called <code>partial application</code>. They
can feel free to call it what they like. It serves the same role as currying does in a more strongly
typed language.</p>
</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 with 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>propEq</code>. Let's implement that.</p>
</div>
</section>
<section class="slide">
<h2>Implementing <code>propEq</code></h2>
<h3>Simplest Approach</h3>
<div><textarea class="code" mode="javascript" style="display: none;">var propEq = function(prop, val) {
return function(obj) {
return obj[prop] === val;
};
};</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>
<br/>
<p>Don't worry…</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>propEq</code></h2>
<p>Can we redefine the following in a points-free style?</p>
<div><textarea class="code" mode="javascript" style="display: none;">var propEq = 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, removing the direct reference to <code>obj</code>:</p>
<div><textarea class="code" mode="javascript" style="display: none;">var propEq = 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>Note that 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>propEq</code></h2>
<p>So now this definition makes sense:</p>
<div><textarea class="code" mode="javascript" style="display: none;">var propEq = function(prop, val) {
return pipe(get(prop), eq(val));
};</textarea></div>
<br/>
<p>Note the switch from <code>compose</code> to <code>pipe</code>.</p>
<div class="slide">
<p>This 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 propEq:</p>
</div>
<div class="slide">