-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1279 lines (996 loc) · 43.1 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 lang="en">
<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>A Quick Tour of Functional Programming</title>
<!-- Required stylesheet -->
<link rel="stylesheet" media="screen" href="core/deck.core.css">
<!-- Extension CSS files go here. Remove or add as needed. -->
<link rel="stylesheet" media="screen" href="extensions/goto/deck.goto.css">
<link rel="stylesheet" media="screen" href="extensions/status/deck.status.css">
<link rel="stylesheet" media="screen" href="extensions/scale/deck.scale.css">
<!-- Style theme. More available in /themes/style/ or create your own. -->
<link rel="stylesheet" media="screen" href="themes/style/haskell.css">
<!-- Transition theme. More available in /themes/transition/ or create your own. -->
<link rel="stylesheet" media="screen" href="themes/transition/fade.css">
<!-- Basic black and white print styles -->
<link rel="stylesheet" media="print" href="core/print.css">
<!-- Required Modernizr file -->
<script src="modernizr.custom.js"></script>
<link rel="stylesheet" href="highlight/styles/haskell.css">
</head>
<body>
<div class="deck-container">
<!-- Begin slides. Just make elements with a class of slide. -->
<section class="slide slide-title">
<div class="slide-title-title">
<div class="slide-title-group">
<div class="slide-title-logo"></div>
<h2>A Quick Tour of Haskell</h2>
</div>
<h4>Functional Tools That You Can Take Home!</h4>
</div>
<div class="slide-title-byline">
<h3>By <strong>Bailey Parker</strong></h3>
</div>
</section>
<section class="slide">
<pre class="full"><div class="pre-name"><span>Java</span></div><code class="java"><!--
-->public static void <T extends Comparable<T>> quickSort(T[] arr) {
quickSort(arr, 0, arr.length - 1);
}
private static void <T extends Comparable<T>> quickSort(T[] arr,
int lo,
int hi) {
if (lo < hi) {
int p = partition(arr, lo, hi);
quickSort(arr, lo, p - 1);
quickSort(arr, p + 1, hi);
}
}
private static int <T extends Comparable<T>> partition(T[] arr,
int lo,
int hi) {
T pivot = arr[hi];
int i = lo - 1;
for (int j = lo; j < hi; j++) {
if (arr[j].compareTo(pivot) < 0) {
swap(arr, ++i, j);
}
}
swap(arr, i, j);
}
</code></pre>
</section>
<section class="slide">
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->sort :: [Integer] -> [Integer]
sort [] = []
sort (pivot:xs) = (sort left) ++ [pivot] ++ (sort right)
where left = filter (< pivot) xs
right = filter (>= pivot) xs</code></pre>
</section>
<section class="slide slide-centered">
<pre>
Mutability.java:41: error: method solvePuzzle in class Solver cannot be applied to given types;
solution = solvePuzzle(puzzle);
^
required: int[][],SolvingStrategy
found: int[][]
reason: actual and formal argument lists differ in length
1 error</pre>
</section>
<section class="slide slide-interstitial">
<h2>Learn to ❤ Your Compiler</h2>
</section>
<section class="slide">
<h2>Type Signatures</h2>
<p>Let's start by figuring out the type signatures of Java methods.</p>
<pre><div class="pre-name oneline"><span>Java</span></div><code class="java"><!--
-->static int add(int lhs, int rhs) {
// ...
}</code></pre>
<pre><div class="pre-name oneline"><span>Haskell</span></div><!--
--><code class="haskell">add :: Integer -> Integer -> Integer</code></pre>
<div class="slide">
<p>The argument types are listed in order, followed by the return type.</p>
<pre><div class="pre-name oneline"><span>Java</span></div><code class="java"><!--
-->static double weirdAdd(float lhs, int rhs) {
// ...
}</code></pre>
<pre><div class="pre-name oneline"><span>Haskell</span></div><!--
--><code class="haskell">weirdAdd :: Float -> Integer -> Double</code></pre>
</div>
</section>
<section class="slide">
<h2>More Type Signatures</h2>
<p>Lists use a slightly different syntax.</p>
<pre><div class="pre-name oneline"><span>Java</span></div><code class="java"><!--
-->static float average(int[] numbers) {
// ...
}</code></pre>
<pre><div class="pre-name oneline"><span>Haskell</span></div><!--
--><code class="haskell">average :: [Integer] -> Float</code></pre>
<div class="slide">
<p>But, strings and characters are what you would expect.</p>
<pre><div class="pre-name oneline"><span>Java</span></div><code class="java"><!--
-->static boolean beginsWith(String search, char prefix) {
// ...
}</code></pre>
<pre><div class="pre-name oneline"><span>Haskell</span></div><!--
--><code class="haskell">beginsWith :: String -> Char -> Bool</code></pre>
</div>
</section>
<section class="slide">
<h2>Functions as Arguments</h2>
<p>What if we pass a function as an argument?</p>
<pre><div class="pre-name oneline"><span>Java</span></div><code class="java"><!--
-->static int findNumber(int[] nums, Predicate<Integer> isWanted) {
for (int num : nums) {
if (isWanted.test(num)) { return num; }
}
throw new NumberNotFoundException(i);
}</code></pre>
<pre><div class="pre-name oneline"><span>Java</span></div><code class="java"><!--
-->findNumber(oddNumbers, num -> MathUtils.isPrime(num));</code></pre>
<pre><div class="pre-name oneline"><span>Java</span></div><code class="java"><!--
-->interface Predicate<T> {
boolean test(T t);
}</code></pre>
<pre class="slide"><div class="pre-name oneline"><span>Java</span></div><!--
--><code class="java">findNumber(oddNumbers, MathUtils::isPrime);</code></pre>
<pre class="slide"><!--
--><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->findNumber :: [Integer] -> (Integer -> Bool) -> Integer</code></pre>
</section>
<section class="slide slide-interstitial">
<h2>The Basics</h2>
</section>
<section class="slide">
<h2>Basic Operations</h2>
<p>Math, boolean, and string operations are straightfoward.</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->> 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - 1/15 + 1/17 - 1/19)
3.0418396189294032</code></pre>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->> (True && False) || (True && True)
True</code></pre>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->> 8 /= 2 * 2 * 2 -- not equal
False</code></pre>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->> 1.0 == 1
True</code></pre>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->> "To understand recursion " ++ "we must first understand recursion"
"To understand recursion we must first understand recursion"</code></pre>
</section>
<section class="slide">
<h2>Basic Operations</h2>
<p>But you don't get implicit casting...</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->> "A random number: " ++ 4
<span class="hljs-repl-error"><interactive>:2:24: error:
• No instance for (Num String) arising from the literal ‘4’
• In the second argument of ‘(++)’, namely ‘4’
In the expression: "A random number: " ++ 4</span></code></pre>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->> "A random number: " ++ show 4
"A random number: 4"</code></pre>
<p>Why didn't concatenating a string and integer work? Let's look at the types!</p>
<div class="slide">
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->(++) :: String -> String -> String</code></pre>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->show :: Integer -> String</code></pre>
</div>
</section>
<section class="slide">
<h2>Basic Operations</h2>
<p>As an exercise, let's recall the types of some of these functions</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->(+) :: Integer -> Integer -> Integer
(-) :: Integer -> Integer -> Integer
(*) :: Integer -> Integer -> Integer
(/) :: Integer -> Integer -> Integer
(&&) :: Bool -> Bool -> Bool
(||) :: Bool -> Bool -> Bool
</code></pre>
</section>
<section class="slide">
<h2>Our First Function</h2>
<p>In Java, we'd probably want to express factorial iteratively:</p>
<pre><div class="pre-name oneline"><span>Java</span></div><code class="java"><!--
-->public static int factorial(int n) {
int product = 1;
for (int i = 1; i <= n; i++) {
product *= i;
}
return product;
}</code></pre>
<div class="slide">
<p>But in Haskell, we need to think <strong>recursively</strong>:</p>
<pre><div class="pre-name oneline"><span>Java</span></div><code class="java"><!--
-->public static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}</code></pre>
</div>
</section>
<section class="slide">
<h2>Our First Function</h2>
<pre><div class="pre-name oneline"><span>Java</span></div><code class="java"><!--
-->public static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}</code></pre>
<p>Translated "verbatim" to Haskell, this would look like:</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->factorial :: Integer -> Integer
factorial n = if n == 0
then 1
else n * factorial (n - 1)</code></pre>
<p class="slide">Do you see any issues with these implementations?</p>
</section>
<section class="slide">
<h2>Lists</h2>
<p>The bread and butter of functional programming is lists.</p>
<pre><div class="pre-name oneline"><span>GHCI</span></div><code class="haskell"><!--
-->> ["lists", "must", "be", "homogenous"]
["lists", "must", "be", "homogenous"]</code></pre>
<pre><div class="pre-name oneline"><span>GHCI</span></div><code class="haskell"><!--
-->> ["so", "this", "breaks", 22]
<span class="hljs-repl-error"><interactive>:5:26: error:
• No instance for (Num String) arising from the literal ‘22’
• In the expression: 22
In the expression: ["so", "this", "breaks", 22]</span></code></pre>
<p>The above is syntactic sugar for an important function called <strong>cons</strong>:</p>
<pre><div class="pre-name oneline"><span>GHCI</span></div><code class="haskell"><!--
-->> "cons" : "prepends" : ["to", "lists"]
["cons", "prepends", "to", "lists"]</code></pre>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->(:) :: a -> [a] -> [a]</code></pre>
</section>
<section class="slide">
<h2>Type Variables</h2>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->(:) :: a -> [a] -> [a]</code></pre>
<p>This is similar to generics in Java:</p>
<pre><div class="pre-name oneline"><span>Java</span></div><code class="java"><!--
-->public static <T> T[] cons(T item, T[] items) {
// ...
}</code></pre>
<p>So, <code>a</code> or <code>T</code> can be replaced with any type.</p>
<pre><div class="pre-name oneline"><span>GHCI</span></div><code class="haskell"><!--
-->> 1 : [2, 3]
[1, 2, 3]
> "one" : ["two", "three"]
["one", "two", "three"]</code></pre>
<pre><div class="pre-name oneline"><span>Java</span></div><code class="java"><!--
-->cons(1, new Integer[] {2, 3}); // {1, 2, 3}
cons("uno", new String[] {"dos", "tres"}); // {"uno","dos","tres"}</code></pre>
</section>
<section class="slide">
<h2>Lists</h2>
<p>Strings are just lists of characters!</p>
<pre><div class="pre-name oneline"><span>GHCI</span></div><code class="haskell"><!--
-->> ['J','o','h','n',' ','H','o','p','k','i','n']
"John Hopkin"
> 'J':'o':'h':'n':' ':'H':'o':'p':'k':'i':'n':[]
"John Hopkin"</code></pre>
<p>And concatenation works on generic lists, not just strings!</p>
<pre><div class="pre-name oneline"><span>GHCI</span></div><code class="haskell"><!--
-->> [1, 2, 3] ++ [4, 5, 6]
[1, 2, 3, 4, 5, 6]</code></pre>
<p>And that's because the type of concatenate is actually general:</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->(++) :: [a] -> [a] -> [a]</code></pre>
</section>
<section class="slide">
<h2>Lists</h2>
<p>Constructing lists of numbers is tedious, so we use ranges instead:</p>
<pre><div class="pre-name oneline"><span>GHCI</span></div><code class="haskell"><!--
-->> [1..10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
> [10,9..1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]</code></pre>
</section>
<section class="slide">
<h2>Lists</h2>
<p>There are lots of builtin functions for working with lists.</p>
<pre><div class="pre-name oneline"><span>GHCI</span></div><code class="haskell"><!--
-->> length [2, 3, 4, 5, 6]
5
> intercalate ", " ["foo", "bar", "baz"]
"foo, bar, baz"
> concat [[1, 2, 3], [2, 4, 6]]
[1, 2, 3, 2, 4, 6]
> head ["foo", "bar", "baz"]
"foo"</code></pre>
</section>
<section class="slide">
<h2>Lists</h2>
<p>What about infinite lists?</p>
<pre><div class="pre-name oneline"><span>GHCI</span></div><code class="haskell"><!--
-->> [1..]
[1, 2, 3, 4, 5, -- forever and ever
> head [1..]
1</code></pre>
<div class="slide">
<p>Why doesn't the first one never finish, but the second does?
<strong>Laziness</strong></p>
<div class="slide">
<pre><div class="pre-name oneline"><span>Python</span></div><code class="python"><!--
-->def positive_integers():
i = 1
while True:
yield i
i += 1
> numbers = positive_integers()
> next(numbers)
1
> next(numbers)
2</code></pre>
</div>
</div>
</section>
<section class="slide">
<h2>Lists</h2>
<p>But what happens if we do this:</p>
<pre><div class="pre-name oneline"><span>GHCI</span></div><code class="haskell"><!--
-->> head []
*** Exception: Prelude.head: empty list</code></pre>
<p>This is bad. It compiles, but you get a runtime error. We can do better!</p>
</section>
<section class="slide">
<h2>Guard Syntax</h2>
<p>Our previous implementation is bad, because it uses control structures.</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->factorial :: Integer -> Integer
factorial n = if n == 0
then 1
else n * factorial (n - 1)</code></pre>
<p>The preferred approach when you have conditions is guard syntax:</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->factorial :: Integer -> Integer
factorial n | n == 0 = 1
| otherwise = n * factorial (n - 1)</code></pre>
<p>This syntax also allows multiple branches:</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->factorial :: Integer -> Integer
factorial n | n < 0 = error "complex number"
| n == 0 = 1
| otherwise = n * factorial (n - 1)</code></pre>
<p>But for this there's an even better approach.</p>
</section>
<section class="slide">
<h2>Pattern Matching</h2>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->factorial :: Integer -> Integer
factorial n = if n == 0
then 1
else n * factorial (n - 1)</code></pre>
<p><strong>Pattern matching</strong> works by choosing which expression to evaluate (which
definition of a function to use) based on argument patterns:</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)</code></pre>
<div class="slide">
<p>You can use <code>_</code> (hole) to indicate that you don't care about the value of an
argument (matches any value):</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->ignoreSecond :: a -> b -> a
ignoreSecond a _ = a
</code></pre>
</div>
</section>
<section class="slide">
<h2>Pattern Matching</h2>
<p>As an example say we wanted to write a function to sum a list of numbers:</p>
<pre><div class="pre-name oneline"><span>Python</span></div><code class="python"><!--
-->def sum(numbers):
total = 0
for number in numbers:
total += number
return total</code></pre>
<div class="slide">
<p>We need to write this recursively to translate it to Haskell:</p>
<pre><div class="pre-name oneline"><span>Python</span></div><code class="python"><!--
-->def sum(numbers):
return numbers[0] + sum(numbers[1:])</code></pre>
<p>But you may notice this has a bug!</p>
<div class="slide">
<pre><div class="pre-name oneline"><span>Python</span></div><code class="python"><!--
-->def sum(numbers):
if len(numbers) == 0:
return 0
return numbers[0] + sum(numbers[1:])</code></pre>
</div>
</div>
</section>
<section class="slide">
<h2>Pattern Matching</h2>
<pre><div class="pre-name oneline"><span>Python</span></div><code class="python"><!--
-->def sum(numbers):
if len(numbers) == 0:
return 0
return numbers[0] + sum(numbers[1:])</code></pre>
<p>With a correct Python implementation, we can see a clear path to the Haskell version:</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->sum :: [Integer] -> Integer
sum [] = 0
sum (x:xs) = x + sum xs</code></pre>
</section>
<section class="slide">
<h2>Pattern Matching</h2>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->sum :: [Integer] -> Integer
sum [] = 0
sum (x:xs) = x + sum xs</code></pre>
<p>Cons can be used in pattern matching to destructure lists:</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->sum [1, 2, 3] = sum (1 : [2, 3])
= 1 + sum [2, 3]
= 1 + sum (2 : [3])
= 1 + 2 + sum [3]
= 1 + 2 + sum (3 : [])
= 1 + 2 + 3 + sum []
= 1 + 2 + 3 + 0</code></pre>
<p>This is a useful pattern! We can use it for other operations on lists.</p>
</section>
<section class="slide">
<h2>Pattern Matching</h2>
<p>We can also build a function to compute the product of a list of numbers.</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->sum :: [Integer] -> Integer
sum [] = 0
sum (x:xs) = x + sum xs</code></pre>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->product :: [Integer] -> Integer
product [] = 1
product (x:xs) = x * product xs</code></pre>
<div class="slide">
<p>These work as you would expect:</p>
<pre><div class="pre-name oneline"><span>GHCI</span></div><code class="haskell"><!--
-->> sum [1, 3, 5]
8
> product [1, 3, 5]
15</code></pre>
<p>But wait, isn't <code>n!</code> the product of all integers from <code>1</code> to
<code>n</code>?</p>
</div>
</section>
<section class="slide">
<h2>Pattern Matching</h2>
<p>So, when we originally had:</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->factorial :: Integer -> Integer
factorial n = 1
factorial n = n * factorial (n - 1)</code></pre>
<div class="slide">
<p>We can combine our <code>product</code> and ranges to arrive at:</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->factorial :: Integer -> Integer
factorial n = product [1..n]</code></pre>
<div class="slide">
<div class="take-home-tip">
<h3>Small, Composable Functions</h3>
<p>Prefer small functions that do one thing well. For more complex tasks, compose these
small functions together. This makes you code more easily testable and more obviously
correct.</p>
<p>Also known as the <em>single resposibility principle</em>.</p>
</div>
</div>
</div>
</section>
<section class="slide">
<h2>Pattern Matching</h2>
<p>Returning our list operations, we should notice a pattern:</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->sum :: [Integer] -> Integer
sum [] = 0
sum (x:xs) = x + sum xs
product :: [Integer] -> Integer
product [] = 1
product (x:xs) = x * product xs
train :: Model -> Example -> Model
emptyModel :: Model
-- Leave it to the pros...
machineLearn :: [Example] -> Model
machineLearn [] = emptyModel
machineLearn (x:xs) = train (machineLearn xs) x</code></pre>
<p>All of these have some default value for the base case (empty list), and apply a function
recursively on this list until that base case is reached. There is an opportunity to
refactor!</p>
</section>
<section class="slide">
<h2>Pattern Matching</h2>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->foldl :: (a -> b -> a) -> a -> [b] -> a
foldl _ initial [] = initial
foldl action initial (x:xs) = action (foldl action initial xs) x</code></pre>
<p>The works exactly how our <code>sum</code> did!</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->sum [1, 2] = sum (1 : [2])
= 1 + sum [2]
= 1 + sum (2 : [])
= 1 + 2 + sum []
= 1 + 2 + 0</code></pre>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->foldl f initial [1, 2] = foldl f initial (1 : [2])
= 1 `f` (foldl f initial [2])
= 1 `f` (foldl f initial (2 : []))
= 1 `f` 2 `f` (foldl f initial [])
= 1 `f` 2 `f` initial</code></pre>
</section>
<section class="slide">
<h2>Pattern Matching</h2>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->foldl :: (a -> b -> a) -> a -> [b] -> a</code></pre>
<p>With this behavior extracted, we can rewrite our other functions:</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->sum :: [Integer] -> Integer
sum xs = foldl (+) 0 xs
product :: [Integer] -> Integer
product xs = foldl (*) 1 xs
train :: Model -> Example -> Model
emptyModel :: Model
-- Leave it to the pros...
machineLearn :: [Example] -> Model
machineLearn examples = foldl train emptyModel examples</code></pre>
</section>
<section class="slide">
<h2>Pattern Matching</h2>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->sum xs = foldl (+) 0 xs
product xs = foldl (*) 1 xs
machineLearn examples = foldl train emptyModel examples</code></pre>
<p>This is a worthwhile refactoring, because if for example, we test <code>foldl</code> and
<code>train</code> and are sure that they are correct, then we know that
<code>machineLearn</code> is also correct!</p>
<div class="take-home-tip">
<h3>Don't Repeat Yourself!</h3>
<p>Extract common behavior between functions into a small, composable function to make your
functions easier to reason about and more obviously correct.</p>
</div>
</section>
<section class="slide">
<h2>Pattern Matching</h2>
<p>It turns out there are other functions like this. What if we wanted a list of prime
numbers?</p>
<p>One (naive) way to obtain this is to go through a list of all positive integers and pull
out the ones that are prime.</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->-- Assuming we had a:
isPrime :: Integer -> Bool
primes :: [Integer]
primes = filter isPrime [2..]</code></pre>
<p>We could do this with a function like:</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->filter (a -> Bool) -> [a] -> [a]
filter predicate xs = foldl collect [] xs
where collect :: [a] -> a -> [a]
collect collected item | predicate item = item:collected
| otherwise = collected</code></pre>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->foldl :: (c -> d -> c) -> c -> [d] -> c</code></pre>
</section>
<section class="slide">
<h2>Pattern Matching</h2>
<p>What if we had a list of videos that we needed to re-encode for different clients
(different qualities and sizes for mobile devices, for example) for a video CDN? We have a
function that does the re-encoding and a list of videos.</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->encodeVideo :: Video -> [EncodedVideo]
encodeVideos :: [Video] -> [[EncodedVideo]]
encodeVideos videos = map encodeVideo videos
map :: (a -> b) -> [a] -> [b]
map f (x:xs) = f x : map f xs</code></pre>
<p>See the mistake? Haskell does!</p>
<div class="slide">
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
--><span class="hljs-repl-error"><interactive>:2:1: warning: [-Wincomplete-patterns]
Pattern match(es) are non-exhaustive
In an equation for ‘map’: Patterns not matched: _ []</span></code></pre>
<div class="slide">
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->map (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x : map f xs</code></pre>
</div>
</div>
</section>
<section class="slide">
<h2>Pattern Matching</h2>
<div class="take-home-tip">
<h3>Check Your Cases</h3>
<p>Use enums and inversion of control to have the compiler check that you have implemented
all cases. In switch statements, the compilers can usually point out missed cases. In other
cases, instead of code like this:</p>
<pre><div class="pre-name oneline"><span>Java</span></div><code class="java"><!--
-->if (entry instanceof Book) {
return ((Book) entry).getIsbn();
} else if (entry instanceof Movie) {
return ((Movie) entry).getBarcode();
}</code></pre>
<p>Prefer code like this:</p>
<pre><div class="pre-name oneline"><span>Java</span></div><code class="java"><!--
-->interface Identifiable {
public String getIdentifier();
}
class Book implements Identifiable {
public String getIdentifier() { return this.getIsbn(); }
}
class Movie implements Identifiable {
public String getIdentifier() { return this.getBarcode(); }
}
// And then use it like...
return entry.getIdentifier();</code></pre>
</div>
</section>
<section class="slide">
<h2>Pattern Matching</h2>
<p>What if we want to consider pairs of items from two lists at the same time?</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->zip :: [a] -> [b] -> [(a, b)]
zip (x:xs) (y:ys) = (x, y) : zip xs ys
zip _ _ = []</code></pre>
<pre><div class="pre-name oneline"><span>GHCI</span></div><code class="haskell"><!--
-->> zip ["Compilers", "PL", "Parallel"] [62, 95, 89]
[("Compilers", 62), ("PL", 95), ("Parallel", 89)]</code></pre>
<p>This family of functions leads us to our next tip:</p>
<div class="take-home-tip">
<h3>Use Lazy Functional Utilities</h3>
<p>Prefer lazy functional tools like <code>map</code>, <code>filter</code>,
<code>zip</code>. They don't construct lists in memory, so they're often more
efficient.</p>
<p>Python has functions of this name. In Java 8, look at the
<a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html">
Stream API</a>.</p>
</div>
</section>
<section class="slide">
<h2>Pattern Matching</h2>
<p>As an example, instead of doing:</p>
<pre><div class="pre-name oneline"><span>Python</span></div><code class="python"><!--
-->courses = ["Compilers", "PL", "Parallel"]
grades = [62, 95, 89]
for i, course in enumerate(courses):
print(f'I got a {grades[i]} in {course}!')</code></pre>
<p>Prefer this:</p>
<pre><div class="pre-name oneline"><span>Python</span></div><code class="python"><!--
-->courses = ["Compilers", "PL", "Parallel"]
grades = [62, 95, 89]
for course, grade in zip(courses, grades):
print(f'I got a {grade} in {course}!')</code></pre>
<p>Because there are no explicit indexes, it's hard to pair two things incorrectly. And
you'll also never run into any <code>IndexError</code>s or
<code>ArrayOutOfBoundsException</code>s!</p>
</section>
<section class="slide">
<h2>Currying</h2>
<p>In Haskell, a function always takes one parameter and returns some value.</p>
<div class="slide">
<p>Wait, <strong>what?</strong></p>
<div class="slide">
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->(+) :: Integer -> (Integer -> Integer)
(1 +) :: Integer -> Integer
(1 + 1) :: Integer</code></pre>
<div class="slide">
<p>This means we can do:</p>
<pre><div class="pre-name oneline"><span>GHCI</span></div><code class="haskell"><!--
-->> map (2 *) [1..5]
[2, 4, 6, 8, 10]</code></pre>
</div>
</div>
</div>
</section>
<section class="slide slide-interstitial">
<h2>Putting It All Together</h2>
</section>
<section class="slide">
<h2>Quicksort</h2>
<p>Can you implement quicksort correctly from memory? Do you get all of the bounds correct?
How about the termination conditions?</p>
<pre class="full"><div class="pre-name"><span>Java</span></div><code class="java"><!--
-->public static void <T extends Comparable<T>> quickSort(T[] arr) {
quickSort(arr, 0, arr.length - 1);
}
private static void <T extends Comparable<T>> quickSort(T[] arr,
int lo,
int hi) {
if (lo < hi) {
int p = partition(arr, lo, hi);
quickSort(arr, lo, p - 1);
quickSort(arr, p + 1, hi);
}
}
private static int <T extends Comparable<T>> partition(T[] arr,
int lo,
int hi) {
T pivot = arr[hi];
int i = lo - 1;
for (int j = lo; j < hi; j++) {
if (arr[j].compareTo(pivot) < 0) {
swap(arr, ++i, j);
}
}
swap(arr, i, j);
}
</code></pre>
</section>
<section class="slide">
<h2>Quicksort</h2>
<p>Wouldn't you rather write?</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->sort :: [Integer] -> [Integer]
sort [] = []
sort (pivot:xs) = (sort left) ++ [pivot] ++ (sort right)
where left = filter (< pivot) xs
right = filter (>= pivot) xs</code></pre>
</section>
<section class="slide">
<h3>Typeclasses</h3>
<p>What if we wanted to make a quicksort work for lists of anything that can be ordered?</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->sort :: [a] -> [a]
sort [] = []
sort (pivot:xs) = (sort left) ++ [pivot] ++ (sort right)
where left = filter (< pivot) xs
right = filter (>= pivot) xs
<span class="hljs-repl-error"><interactive>:16:24: error:
• No instance for (Ord a) arising from a use of ‘<’
Possible fix:
add (Ord a) to the context of the type signature for:
sort :: forall a. [a] -> [a]
• In the first argument of ‘filter’, namely ‘(< pivot)’
In the expression: filter (< pivot) xs
In an equation for ‘left’: left = filter (< pivot) xs
<interactive>:17:25: error:
• No instance for (Ord a) arising from a use of ‘>=’
Possible fix:
add (Ord a) to the context of the type signature for:
sort :: forall a. [a] -> [a]
• In the first argument of ‘filter’, namely ‘(>= pivot)’
In the expression: filter (>= pivot) xs
In an equation for ‘right’: right = filter (>= pivot) xs</span></code></pre>
</section>
<section class="slide">
<h2>Typeclasses</h2>
<p>So let's take its advice!</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->sort :: Ord a => [a] -> [a]
sort [] = []
sort (pivot:xs) = (sort left) ++ [pivot] ++ (sort right)
where left = filter (< pivot) xs
right = filter (>= pivot) xs</code></pre>
<p>So why did this work?</p>
<div class="slide">
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->class Ord a where
compare :: a -> a -> Ordering -- either LT, EQ, or GT</code></pre>
</div>
</section>
<section class="slide">
<h2>Typeclasses</h2>
<p>Other interesting typeclasses:</p>
<pre><div class="pre-name oneline"><span>Haskell</span></div><code class="haskell"><!--
-->class Eq a where
(==) :: a -> a -> Bool
class Show a where