-
Notifications
You must be signed in to change notification settings - Fork 3
/
lec-go-1-functions-data.html
1841 lines (1565 loc) · 89.6 KB
/
lec-go-1-functions-data.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
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta name="generator" content="pandoc" />
<meta name="author" content="Martin Sulzmann" />
<title>Google Go (golang) Part 1: Introduction</title>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
div.sourceCode { overflow-x: auto; }
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; line-height: 100%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > span.kw { color: #007020; font-weight: bold; } /* Keyword */
code > span.dt { color: #902000; } /* DataType */
code > span.dv { color: #40a070; } /* DecVal */
code > span.bn { color: #40a070; } /* BaseN */
code > span.fl { color: #40a070; } /* Float */
code > span.ch { color: #4070a0; } /* Char */
code > span.st { color: #4070a0; } /* String */
code > span.co { color: #60a0b0; font-style: italic; } /* Comment */
code > span.ot { color: #007020; } /* Other */
code > span.al { color: #ff0000; font-weight: bold; } /* Alert */
code > span.fu { color: #06287e; } /* Function */
code > span.er { color: #ff0000; font-weight: bold; } /* Error */
code > span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
code > span.cn { color: #880000; } /* Constant */
code > span.sc { color: #4070a0; } /* SpecialChar */
code > span.vs { color: #4070a0; } /* VerbatimString */
code > span.ss { color: #bb6688; } /* SpecialString */
code > span.im { } /* Import */
code > span.va { color: #19177c; } /* Variable */
code > span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code > span.op { color: #666666; } /* Operator */
code > span.bu { } /* BuiltIn */
code > span.ex { } /* Extension */
code > span.pp { color: #bc7a00; } /* Preprocessor */
code > span.at { color: #7d9029; } /* Attribute */
code > span.do { color: #ba2121; font-style: italic; } /* Documentation */
code > span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code > span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code > span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
</style>
<link rel="stylesheet" type="text/css" media="screen, projection, print"
href="http://www.w3.org/Talks/Tools/Slidy2/styles/slidy.css" />
<script src="http://www.w3.org/Talks/Tools/Slidy2/scripts/slidy.js"
charset="utf-8" type="text/javascript"></script>
</head>
<body>
<div class="slide titlepage">
<h1 class="title">Google Go (golang) Part 1: Introduction</h1>
<p class="author">
Martin Sulzmann
</p>
</div>
<div id="google-go-golang" class="slide section level1">
<h1>Google Go (golang)</h1>
<p><a href="Go">http://golang.org/</a></p>
<ul>
<li>Go the better C?</li>
<li>Statically typed/Simple form of type inference</li>
<li>Higher-order functions</li>
<li>Garbage Collection</li>
<li>Method overloading + Interfaces</li>
<li>Concurrency
<ul>
<li>Light-weight threads</li>
<li>Channel-based communication
<ul>
<li>Formal foundations: Communicating Sequential Processes, Sir Tony Hoare</li>
</ul></li>
<li>Philosophy: “Do not communicate by sharing memory. Instead share by communicating.”</li>
</ul></li>
</ul>
</div>
<div id="hello-world" class="slide section level1">
<h1>Hello World</h1>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">package</span> main
<span class="kw">import</span> <span class="st">"fmt"</span>
<span class="kw">var</span> x <span class="dt">int</span>
<span class="kw">func</span> hi(y <span class="dt">int</span>) {
fmt.Printf(<span class="st">"hi %d</span><span class="ch">\n</span><span class="st">"</span>,y)
}
<span class="kw">func</span> main() {
x= <span class="dv">1</span>
hi(x)
fmt.Printf(<span class="st">"hello, world</span><span class="ch">\n</span><span class="st">"</span>)
}</code></pre></div>
<ul>
<li>Type declarations in 'proper' order
<ul>
<li><code>var varName varType</code></li>
<li>Variable <code>varName</code> of Type <code>varType</code></li>
</ul></li>
</ul>
</div>
<div id="go-toolchain" class="slide section level1">
<h1>Go Toolchain</h1>
<ul>
<li>Comand line:
<ul>
<li><p><code>go run hello.go</code></p></li>
<li><code>gofmt hello.go</code>
<ul>
<li>"pretty printer"</li>
<li>Per Default to standard I/O</li>
<li>Or bei overwriting content <code>gofmt -w hello.go</code></li>
</ul></li>
<li><p>Choose your editor (emacs, ...)</p></li>
</ul></li>
<li>IDE: <a href="IDE%20Go">http://code.google.com/p/liteide/</a></li>
</ul>
<p>In most cases, our programs consist of a single file.</p>
</div>
<div id="simple-form-of-type-inference" class="slide section level1">
<h1>Simple form of type inference</h1>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">package</span> main
<span class="kw">import</span> <span class="st">"fmt"</span>
<span class="kw">func</span> main() {
<span class="kw">var</span> x <span class="dt">int</span>
x = <span class="dv">1</span>
y := x + <span class="dv">1</span>
fmt.Printf(<span class="st">"y = %d"</span>, y)
}</code></pre></div>
<p>The type of <code>y</code> is inferred by the right-hand side.</p>
<p>Pretty convenient!</p>
<p>Languages like Haskell support <em>full</em> type inference where the types of functions can be inferred.</p>
</div>
<div id="control-structures---for-loop" class="slide section level1">
<h1>Control structures - for loop</h1>
<p>The only control structure.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"> <span class="kw">for</span> i := <span class="dv">0</span>; i < <span class="dv">5</span>; i++ {
fmt.Printf(<span class="st">"Value of i is now: %d </span><span class="ch">\n</span><span class="st">"</span>, i)
}</code></pre></div>
<p>Infinite loop with <code>break</code></p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"> <span class="kw">for</span> {
<span class="kw">if</span> j > <span class="dv">5</span> {
<span class="kw">break</span>
}
fmt.Printf(<span class="st">"Value of j is now: %d </span><span class="ch">\n</span><span class="st">"</span>, j)
j++
}</code></pre></div>
<h2 id="complete-example">Complete example</h2>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">package</span> main
<span class="kw">import</span> <span class="st">"fmt"</span>
<span class="kw">func</span> main() {
<span class="kw">for</span> i := <span class="dv">0</span>; i < <span class="dv">5</span>; i++ {
fmt.Printf(<span class="st">"Value of i is now: %d </span><span class="ch">\n</span><span class="st">"</span>, i)
}
j := <span class="dv">0</span>
<span class="kw">for</span> {
<span class="kw">if</span> j > <span class="dv">5</span> {
<span class="kw">break</span>
}
fmt.Printf(<span class="st">"Value of j is now: %d </span><span class="ch">\n</span><span class="st">"</span>, j)
j++
}
}</code></pre></div>
</div>
<div id="arrays" class="slide section level1">
<h1>Arrays</h1>
<p>Out of bounds check.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"> <span class="kw">var</span> s1 [<span class="dv">3</span>]<span class="dt">string</span>
s1[<span class="dv">0</span>] = <span class="st">"one"</span>
s1[<span class="dv">1</span>] = <span class="st">"two"</span>
s1[<span class="dv">2</span>] = <span class="st">"three"</span>
<span class="co">// s1[3] = "four"</span></code></pre></div>
<p>Short-hand array initialization</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"> s2 := [<span class="dv">3</span>]<span class="dt">string</span>{<span class="st">"one"</span>, <span class="st">"two"</span>, <span class="st">"three"</span>}</code></pre></div>
<p>Iteration</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"> <span class="kw">for</span> index, elem := <span class="kw">range</span> s1 {
fmt.Printf(<span class="st">"%d %s </span><span class="ch">\n</span><span class="st">"</span>, index, elem)
}</code></pre></div>
<h2 id="complete-example-1">Complete example</h2>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">package</span> main
<span class="kw">import</span> <span class="st">"fmt"</span>
<span class="kw">func</span> main() {
<span class="kw">var</span> s1 [<span class="dv">3</span>]<span class="dt">string</span>
s1[<span class="dv">0</span>] = <span class="st">"one"</span>
s1[<span class="dv">1</span>] = <span class="st">"two"</span>
s1[<span class="dv">2</span>] = <span class="st">"three"</span>
<span class="kw">for</span> index, elem := <span class="kw">range</span> s1 {
fmt.Printf(<span class="st">"%d %s </span><span class="ch">\n</span><span class="st">"</span>, index, elem)
}
s2 := [<span class="dv">3</span>]<span class="dt">string</span>{<span class="st">"one"</span>, <span class="st">"two"</span>, <span class="st">"three"</span>}
fmt.Printf(<span class="st">"%s"</span>, s2[<span class="dv">0</span>])
}</code></pre></div>
</div>
<div id="slices" class="slide section level1">
<h1>Slices</h1>
<p>More flexible arrays (length may change)</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"> s1 := <span class="fu">make</span>([]<span class="dt">string</span>, <span class="dv">3</span>)</code></pre></div>
<p>Short-hand</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"> s2 := []<span class="dt">string</span>{<span class="st">"a"</span>, <span class="st">"b"</span>}</code></pre></div>
<p>Functions on slices, e.g. <code>append</code></p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"> s2 := []<span class="dt">string</span>{<span class="st">"a"</span>, <span class="st">"b"</span>}
s3 := <span class="fu">append</span>(s2, <span class="st">"c"</span>, <span class="st">"d"</span>, <span class="st">"e"</span>)</code></pre></div>
<h2 id="complete-example-2">Complete example</h2>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">package</span> main
<span class="kw">import</span> <span class="st">"fmt"</span>
<span class="kw">func</span> printSlice(s []<span class="dt">string</span>) {
<span class="kw">for</span> _, elem := <span class="kw">range</span> s {
fmt.Printf(<span class="st">"%s </span><span class="ch">\n</span><span class="st">"</span>, elem)
}
}
<span class="kw">func</span> main() {
s1 := <span class="fu">make</span>([]<span class="dt">string</span>, <span class="dv">3</span>)
s1[<span class="dv">0</span>] = <span class="st">"one"</span>
s1[<span class="dv">1</span>] = <span class="st">"two"</span>
s1[<span class="dv">2</span>] = <span class="st">"three"</span>
printSlice(s1)
s2 := []<span class="dt">string</span>{<span class="st">"a"</span>, <span class="st">"b"</span>}
s3 := <span class="fu">append</span>(s2, <span class="st">"c"</span>, <span class="st">"d"</span>, <span class="st">"e"</span>)
printSlice(s3)
}</code></pre></div>
</div>
<div id="functions---return-values" class="slide section level1">
<h1>Functions - Return values</h1>
<ul>
<li>Return types in 'proper' order</li>
</ul>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> inc(i <span class="dt">int</span>) <span class="dt">int</span></code></pre></div>
<ul>
<li>Multiple return values</li>
</ul>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> myDiv2(x <span class="dt">int</span>, y <span class="dt">int</span>) (<span class="dt">int</span>, <span class="dt">bool</span>)</code></pre></div>
<ul>
<li>Complete example</li>
</ul>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">package</span> main
<span class="kw">import</span> <span class="st">"fmt"</span>
<span class="kw">func</span> inc(i <span class="dt">int</span>) <span class="dt">int</span> { <span class="kw">return</span> i + <span class="dv">1</span> }
<span class="co">// Direct reference to return values by name</span>
<span class="kw">func</span> myDiv(x <span class="dt">int</span>, y <span class="dt">int</span>) (res <span class="dt">int</span>, status <span class="dt">bool</span>) {
status = <span class="ot">false</span>
<span class="kw">if</span> y == <span class="dv">0</span> {
<span class="kw">return</span>
}
res = x / y
status = <span class="ot">true</span>
<span class="kw">return</span>
}
<span class="kw">func</span> myDiv2(x <span class="dt">int</span>, y <span class="dt">int</span>) (<span class="dt">int</span>, <span class="dt">bool</span>) {
<span class="kw">if</span> y == <span class="dv">0</span> {
<span class="kw">return</span> <span class="dv">0</span>, <span class="ot">false</span>
}
<span class="kw">return</span> x / y, <span class="ot">true</span>
}
<span class="kw">func</span> main() {
<span class="kw">var</span> res <span class="dt">int</span>
<span class="kw">var</span> status <span class="dt">bool</span>
res, status = myDiv(inc(<span class="dv">3</span>), <span class="dv">2</span>)
fmt.Printf(<span class="st">"Result = %d </span><span class="ch">\n</span><span class="st">"</span>, res)
fmt.Printf(<span class="st">"Status = %t </span><span class="ch">\n</span><span class="st">"</span>, status)
res, status = myDiv2(<span class="dv">1</span>, <span class="dv">0</span>)
fmt.Printf(<span class="st">"Result = %d </span><span class="ch">\n</span><span class="st">"</span>, res)
fmt.Printf(<span class="st">"Status = %t </span><span class="ch">\n</span><span class="st">"</span>, status)
}</code></pre></div>
</div>
<div id="higher-order-functions" class="slide section level1">
<h1>Higher-order functions</h1>
<ul>
<li>Function prototypes</li>
</ul>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">type</span> Type0 <span class="kw">func</span>()
<span class="kw">type</span> Type1 <span class="kw">func</span>(<span class="dt">int</span>) <span class="dt">int</span>
<span class="kw">type</span> Type2 <span class="kw">func</span>(<span class="dt">int</span>)</code></pre></div>
<ul>
<li>Function as arguments</li>
</ul>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> apply(i <span class="dt">int</span>, f Type1) <span class="dt">int</span> {
<span class="kw">return</span> f(i)
}
<span class="kw">func</span> execute(f Type0) {
f()
}</code></pre></div>
<ul>
<li>Functions as return values</li>
</ul>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> hello2(x <span class="dt">int</span>) Type0 {
<span class="kw">return</span> <span class="kw">func</span>() { fmt.Printf(<span class="st">"Hello %d </span><span class="ch">\n</span><span class="st">"</span>, x) }
}</code></pre></div>
<ul>
<li>Complete example</li>
</ul>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">package</span> main
<span class="kw">import</span> <span class="st">"fmt"</span>
<span class="kw">type</span> Type0 <span class="kw">func</span>()
<span class="kw">type</span> Type1 <span class="kw">func</span>(<span class="dt">int</span>) <span class="dt">int</span>
<span class="kw">type</span> Type2 <span class="kw">func</span>(<span class="dt">int</span>)
<span class="kw">func</span> inc(i <span class="dt">int</span>) <span class="dt">int</span> { <span class="kw">return</span> i + <span class="dv">1</span> }
<span class="kw">func</span> apply(i <span class="dt">int</span>, f Type1) <span class="dt">int</span> {
<span class="kw">return</span> f(i)
}
<span class="kw">func</span> execute(f Type0) {
f()
}
<span class="kw">func</span> hello() {
fmt.Print(<span class="st">"Hello </span><span class="ch">\n</span><span class="st">"</span>)
}
<span class="kw">func</span> hello2(x <span class="dt">int</span>) Type0 {
<span class="kw">return</span> <span class="kw">func</span>() { fmt.Printf(<span class="st">"Hello %d </span><span class="ch">\n</span><span class="st">"</span>, x) }
}
<span class="kw">func</span> main() {
execute(hello)
execute(hello2(<span class="dv">2</span>))
fmt.Printf(<span class="st">"%d </span><span class="ch">\n</span><span class="st">"</span>, apply(<span class="dv">1</span>, inc))
}</code></pre></div>
</div>
<div id="partial-function-application" class="slide section level1">
<h1>Partial function application</h1>
<p>Consider</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> plus(x <span class="dt">int</span>, y <span class="dt">int</span>) <span class="dt">int</span> {
<span class="kw">return</span> x+y
}</code></pre></div>
<p>The arguments to <code>plus</code> must be both present.</p>
<p>In Go, it's possible to 'incrementally' supply addition with its arguments.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> add(x <span class="dt">int</span>) <span class="kw">func</span>(<span class="dt">int</span>) <span class="dt">int</span> {
<span class="kw">return</span> <span class="kw">func</span>(y <span class="dt">int</span>) <span class="dt">int</span> { <span class="kw">return</span> x + y }
}</code></pre></div>
<p>Function <code>add</code> expects an integer argument (left operand) and yields a function. This function expects another integer argument (right operand) and then yields the expected result.</p>
<p>Being able to supply function arguments incrementally gives us more flexibility. Here is a neat way to define the increment function.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> inc(x <span class="dt">int</span>) <span class="dt">int</span> {
<span class="kw">return</span> add(<span class="dv">1</span>)(x)
}</code></pre></div>
<ul>
<li><p>`add(1) yields a function from integer to integer</p></li>
<li><p><code>add(1)(x)</code> then yields the incremented <code>x</code> value</p></li>
</ul>
<p>Slight variation of the above.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"> plus := <span class="kw">func</span>(x <span class="dt">int</span>) <span class="kw">func</span>(<span class="dt">int</span>) <span class="dt">int</span> {
<span class="kw">return</span> <span class="kw">func</span>(y <span class="dt">int</span>) <span class="dt">int</span> { <span class="kw">return</span> x + y }
}
inc := plus(<span class="dv">1</span>)</code></pre></div>
<h2 id="connection-to-oo">Connection to OO</h2>
<p>In Go functions are first-class (that is, they can appear anywwhere). This is similar to OO where objects are first-class.</p>
<p>For example, in an OO language, we can call a method <code>m1</code> on some object <code>o1</code>. The result is an object on which we call another method <code>m2</code>.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go">o1.m1().m2()</code></pre></div>
</div>
<div id="function-closures" class="slide section level1">
<h1>Function closures</h1>
<p>What's the output of the following program?</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">package</span> main
<span class="kw">import</span> <span class="st">"fmt"</span>
<span class="kw">type</span> Type0 <span class="kw">func</span>()
<span class="kw">func</span> main() {
<span class="kw">var</span> fn Type0
<span class="kw">var</span> x <span class="dt">int</span> = <span class="dv">2</span>
fn = <span class="kw">func</span>() { fmt.Printf(<span class="st">"%d </span><span class="ch">\n</span><span class="st">"</span>, x) }
fn()
x = <span class="dv">3</span>
fn()
}</code></pre></div>
</div>
<div id="structs" class="slide section level1">
<h1>Structs</h1>
<ul>
<li>Go is an object-oriented language</li>
<li>No <code>class</code> keyword, use <code>struct</code></li>
</ul>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">type</span> rectangle <span class="kw">struct</span> {
length <span class="dt">int</span>
width <span class="dt">int</span>
}</code></pre></div>
<ul>
<li>Construction of values</li>
</ul>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"> <span class="kw">var</span> r1 rectangle = rectangle{<span class="dv">1</span>, <span class="dv">2</span>}
<span class="kw">var</span> r2 rectangle = rectangle{width: <span class="dv">2</span>, length: <span class="dv">1</span>}
r3 := rectangle{width: <span class="dv">2</span>, length: <span class="dv">1</span>}</code></pre></div>
<p>Either by position or by field reference.</p>
<p>Go supports type inference of auto variables (like C++11).</p>
</div>
<div id="structs---methods" class="slide section level1">
<h1>Structs - Methods</h1>
<p>Methods are defined separately</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> (r rectangle) area() <span class="dt">int</span> {
<span class="kw">return</span> r.length * r.width
}</code></pre></div>
<p>There is no <code>self</code> or <code>this</code>. Struct values are always referenced by name.</p>
<p>In the above, <code>r</code> is passed to <code>area</code> as a value. We must use call-by reference if we wish to update <code>r</code>'s field values.</p>
<ul>
<li>Methods and call-by reference</li>
</ul>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> (r *rectangle) scale(s <span class="dt">int</span>) {
r.length = r.length * s
r.width = r.width * s
}</code></pre></div>
<p>The <code>*</code> indicates that we pass <code>r</code> to <code>scale</code> by reference. Thus, the update is globally visible.</p>
<ul>
<li>Automatic conversions</li>
</ul>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go">r1.scale(<span class="dv">3</span>)
(&r1).scale(<span class="dv">3</span>)</code></pre></div>
<p>The above statements are equivalent. Go will automatically perform the conversion.</p>
<ul>
<li>Complete example</li>
</ul>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">package</span> main
<span class="kw">import</span> <span class="st">"fmt"</span>
<span class="kw">type</span> rectangle <span class="kw">struct</span> {
length <span class="dt">int</span>
width <span class="dt">int</span>
}
<span class="kw">func</span> (r rectangle) area() <span class="dt">int</span> {
<span class="kw">return</span> r.length * r.width
}
<span class="kw">func</span> (r *rectangle) scale(s <span class="dt">int</span>) {
r.length = r.length * s
r.width = r.width * s
}
<span class="kw">func</span> main() {
<span class="kw">var</span> r1 rectangle = rectangle{<span class="dv">1</span>, <span class="dv">2</span>}
<span class="kw">var</span> r2 rectangle = rectangle{width: <span class="dv">2</span>, length: <span class="dv">1</span>}
r3 := rectangle{width: <span class="dv">2</span>, length: <span class="dv">1</span>}
r3.scale(<span class="dv">3</span>)
fmt.Printf(<span class="st">"%d </span><span class="ch">\n</span><span class="st">"</span>, r1.area()+r2.area()+r3.area())
}</code></pre></div>
</div>
<div id="structs---further-stuff" class="slide section level1">
<h1>Structs - Further stuff</h1>
<ul>
<li><p>Encapsulation and visibility</p></li>
<li><p>Mimicing inheritance via annonymous fields</p></li>
<li><p>...</p></li>
</ul>
</div>
<div id="method-overloading-interfaces" class="slide section level1">
<h1>Method overloading + Interfaces</h1>
<h2 id="highlights">Highlights</h2>
<p><b>Overloading</b>. Define a function, method, operator with the same name in the same scope.</p>
<p>Go supports <em>method overloading</em> where method dispatch is based on the "receiver" type. Consider the example</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">type</span> Int <span class="kw">struct</span> { val <span class="dt">int</span> }
<span class="kw">func</span> (i Int) plus(x <span class="dt">int</span>) <span class="dt">int</span> {
<span class="kw">return</span> i.val + x
}
<span class="kw">type</span> MyFloat32 <span class="dt">float32</span>
<span class="kw">func</span> (f MyFloat32) plus(x <span class="dt">float32</span>) <span class="dt">float32</span> {
<span class="kw">return</span> (<span class="dt">float32</span>(f)) + x
}</code></pre></div>
<ul>
<li><p>(Overloaded) methods takes as argument a receiver type which is the argument preceeding the method name.</p></li>
<li><p>These receivers must be user-defined types (introduced via the <code>type</code> keyword).</p></li>
<li><p>The type <code>MyFloat32</code> is a new type but is ismorphic to the built-in type <code>float32</code>.</p></li>
<li><p>The choice which method is called (method dispatch) depends on the receiver type.</p></li>
<li><p>The calling convention for methods in Go resembles the common "dot" notation used in OO language. For example, consider</p></li>
</ul>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"> i := Int {<span class="dv">1</span>}
r1 := i.plus(<span class="dv">1</span>)
f := MyFloat32 (<span class="dv">1</span><span class="fl">.0</span>)
r2 := f.plus(<span class="dv">1</span><span class="fl">.0</span>) </code></pre></div>
<p><b>Interfaces</b> are contracts between expected behavior and actual implementation.</p>
<p>In Go, we can build a common interface for overloaded methods. Consider</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">type</span> ADDInt <span class="kw">interface</span> {
addInt(<span class="dt">int</span>) <span class="dt">float32</span>
}</code></pre></div>
<p>Interfaces can appear as arguments and return values.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> useAdd(a ADDInt, x <span class="dt">int</span>) <span class="dt">float32</span> {
<span class="kw">return</span> a.addInt(x)
}</code></pre></div>
<p>Actual implementations are provided as overloaded methods</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> (i Int) addInt(x <span class="dt">int</span>) <span class="dt">float32</span> {
<span class="kw">return</span> <span class="dt">float32</span> (i.val + x)
}
<span class="kw">func</span> (f MyFloat32) addInt(x <span class="dt">int</span>) <span class="dt">float32</span> {
<span class="kw">return</span> (<span class="dt">float32</span>(f)) + <span class="dt">float32</span> (x)
}</code></pre></div>
<p>and the concrete instances are selected based on the arguments provided for interfaces.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"> a1 := useAdd(Int{<span class="dv">2</span>},<span class="dv">2</span>)
a2 := useAdd(MyFloat32 (<span class="dv">2</span><span class="fl">.0</span>),<span class="dv">2</span>)</code></pre></div>
<p>In Go, interfaces can be nested and actual implementations added at any time.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">type</span> MULTInt <span class="kw">interface</span> {
multInt(<span class="dt">int</span>) <span class="dt">float32</span>
ADDInt
}
<span class="kw">func</span> useAddMult(a MULTInt, x <span class="dt">int</span>) <span class="dt">float32</span> {
<span class="kw">return</span> a.addInt(x) + a.multInt(x)
}</code></pre></div>
<p>The Go type system guarantees that actual implementations are available.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> (i Int) multInt(x <span class="dt">int</span>) <span class="dt">float32</span> {
<span class="kw">return</span> <span class="dt">float32</span> (i.val * x)
}
m1 := useAddMult(Int{<span class="dv">2</span>},<span class="dv">2</span>) <span class="co">// type checks</span>
m2 := useAddMult(Float32 (<span class="dv">2</span><span class="fl">.0</span>),<span class="dv">2</span>) <span class="co">// yields type error!</span></code></pre></div>
<p>We encounter a type error because the MultInt instance on type <code>Float32</code> can not be satisfied (because there is no such definition for <code>multInt</code>).</p>
<h2 id="short-summary">Short summary</h2>
<ul>
<li><p>Method names in an interface hierarchy must be distinct.</p></li>
<li><p>Interface hierarchies must be acyclic.</p></li>
<li><p>Method names can appear in distinct interfaces.</p></li>
<li><p>Via interfaces + method overloading, Go supports a (limited) form of "ad-hoc polymorphism".</p></li>
</ul>
<h2 id="any-interface">"Any" Interface</h2>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"> <span class="kw">interface</span>{}</code></pre></div>
<pre><code>Any interface. Similar to the type `Object` in Java.
We can perform some run-time type cast.</code></pre>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"> <span class="kw">func</span> any(anything <span class="kw">interface</span>{}) {
<span class="kw">switch</span> v := anything.(<span class="kw">type</span>) {
<span class="kw">case</span> <span class="dt">int</span>:
fmt.Printf(<span class="st">"some int %d </span><span class="ch">\n</span><span class="st">"</span>, v)
<span class="kw">case</span> rectangle:
fmt.Println(v)
r := anything.(rectangle)
fmt.Printf(<span class="st">"length = %d, width = %d </span><span class="ch">\n</span><span class="st">"</span>, r.length, r.width)
<span class="kw">default</span>:
fmt.Println(<span class="st">"don't know"</span>)
}
}</code></pre></div>
<pre><code>* We can also cast to a specific type, see `anything.(rectangle)`
* Such a cast may fail
* We can catch failure via</code></pre>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"> r, ok := anything.(rectangle)</code></pre></div>
<pre><code>`ok` equals false in case the cast fails
* BTW, Go automatically performs a `break` after each case.
* Complete example</code></pre>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"> <span class="kw">package</span> main
<span class="kw">import</span> <span class="st">"fmt"</span>
<span class="kw">type</span> rectangle <span class="kw">struct</span> {
length <span class="dt">int</span>
width <span class="dt">int</span>
}
<span class="kw">func</span> any(anything <span class="kw">interface</span>{}) {
<span class="kw">switch</span> v := anything.(<span class="kw">type</span>) {
<span class="kw">case</span> <span class="dt">int</span>:
fmt.Printf(<span class="st">"some int %d </span><span class="ch">\n</span><span class="st">"</span>, v)
<span class="kw">case</span> rectangle:
fmt.Println(v)
r := anything.(rectangle)
fmt.Printf(<span class="st">"length = %d, width = %d </span><span class="ch">\n</span><span class="st">"</span>, r.length, r.width)
<span class="kw">default</span>:
fmt.Println(<span class="st">"don't know"</span>)
}
}
<span class="kw">func</span> main() {
any(<span class="dv">1</span>)
any(rectangle{<span class="dv">1</span>, <span class="dv">2</span>})
}</code></pre></div>
<h2 id="further-examples">Further examples</h2>
<h3 id="shapes">Shapes</h3>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">type</span> shape <span class="kw">interface</span> {
area() <span class="dt">int</span>
}</code></pre></div>
<p>Some functions which assume a shape behavior.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> shapeTwo(sh1, sh2 shape) <span class="dt">int</span> {
<span class="kw">return</span> sh1.area() + sh2.area()
}
<span class="kw">func</span> shapes(shs ...shape) <span class="dt">int</span> {
<span class="kw">var</span> a <span class="dt">int</span> = <span class="dv">0</span>
<span class="kw">for</span> _, elem := <span class="kw">range</span> shs {
a = a + elem.area()
}
<span class="kw">return</span> a
}</code></pre></div>
<p>We can define arguments with a variable number of arguments (of the some type) and iterate over them via a <code>for</code> loop.</p>
<p>In the above we don't care (<code>_</code>) about the index position.</p>
<p>Some concrete instances.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">type</span> rectangle <span class="kw">struct</span> {
length <span class="dt">int</span>
width <span class="dt">int</span>
}
<span class="kw">type</span> square <span class="kw">struct</span> {
length <span class="dt">int</span>
}
<span class="kw">func</span> (r rectangle) area() <span class="dt">int</span> {
<span class="kw">return</span> r.length * r.width
}
<span class="kw">func</span> (s square) area() <span class="dt">int</span> {
<span class="kw">return</span> s.length * s.length
}</code></pre></div>
<ul>
<li>Complete example</li>
</ul>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">package</span> main
<span class="kw">import</span> <span class="st">"fmt"</span>
<span class="kw">type</span> rectangle <span class="kw">struct</span> {
length <span class="dt">int</span>
width <span class="dt">int</span>
}
<span class="kw">type</span> square <span class="kw">struct</span> {
length <span class="dt">int</span>
}
<span class="kw">func</span> (r rectangle) area() <span class="dt">int</span> {
<span class="kw">return</span> r.length * r.width
}
<span class="kw">func</span> (s square) area() <span class="dt">int</span> {
<span class="kw">return</span> s.length * s.length
}
<span class="kw">type</span> shape <span class="kw">interface</span> {
area() <span class="dt">int</span>
}
<span class="kw">func</span> shapeTwo(sh1, sh2 shape) <span class="dt">int</span> {
<span class="kw">return</span> sh1.area() + sh2.area()
}
<span class="kw">func</span> shapes(shs ...shape) <span class="dt">int</span> {
<span class="kw">var</span> a <span class="dt">int</span> = <span class="dv">0</span>
<span class="kw">for</span> _, elem := <span class="kw">range</span> shs {
a = a + elem.area()
}
<span class="kw">return</span> a
}
<span class="kw">func</span> main() {
<span class="kw">var</span> r1 rectangle = rectangle{<span class="dv">1</span>, <span class="dv">2</span>}
<span class="kw">var</span> s1 square = square{<span class="dv">3</span>}
fmt.Printf(<span class="st">"%d </span><span class="ch">\n</span><span class="st">"</span>, r1.area()+s1.area())
fmt.Printf(<span class="st">"%d </span><span class="ch">\n</span><span class="st">"</span>, shapeTwo(r1, s1))
fmt.Printf(<span class="st">"%d </span><span class="ch">\n</span><span class="st">"</span>, shapes(r1, r1, s1, s1, s1))
}</code></pre></div>
</div>
<div id="extended-examples" class="slide section level1">
<h1>Extended Examples</h1>
<ul>
<li><p><b>Regular expression derivatives</b></p>
<ul>
<li>How to mimic pattern matching over algebraic data types in Go.</li>
</ul></li>
<li><p><b>Parser combinators</b></p>
<ul>
<li><p>Playing with higher-order functions.</p></li>
<li><p>Example of embedded (internal) domain-specific language (DSL).</p></li>
<li><p>DSL seperated from host language via types.</p></li>
</ul></li>
</ul>
</div>
<div id="regular-expression-derivatives" class="slide section level1">
<h1>Regular expression derivatives</h1>
<h2 id="some-theory-on-regular-expressions-first">Some theory on regular expressions first</h2>
<h3 id="syntax">Syntax</h3>
<p>In EBNF Syntax:</p>
<pre><code>
r,s ::= x | y | z | ... Symbols aka letters taken from a finite alphabet
| epsilon Empty word
| phi Empty language
| r + r Alternatives
| r . r Sequence aka concatenation
| r* Kleene star
u,v,w ::= epsilon empty word
| w . w concatenation</code></pre>
<p>Sigma denotes the finite set of alphabet symbols.</p>
<p>Regular expressions are popular formalism to specify (infinitely many) patterns of input.</p>
<p>For example,</p>
<pre><code> (open . (read + write)* . close)*</code></pre>
<p>specifies the valid access patterns of a resource usage policy.</p>
<p>We assume that <code>open</code>, <code>read</code>, <code>write</code>, <code>close</code> are the primitive events (symbols) which will be recorded during a program run.</p>
<h3 id="membership">Membership</h3>
<p><code>L(r)</code> denotes the set of words represented by the regular expression r.</p>
<p>Standard (denotational) formulation of L(r):</p>
<pre><code>L(x) = { x }
L(epsilon) = { epsilon }
L(phi) = { }
L(r + s) = { w | w in L(r) or w in L(s) }
L(r . s) = { v . w | v in L(r) and w in L(s) }
L(r*) = { epsilon } cap { w_1 . ... . w_n | w_1, ..., w_n in L(r) and n >=1 }</code></pre>
<h4 id="membership-test-via-derivatives">Membership Test via Derivatives</h4>
<p>The classical approach is to turn the regular expression into an automata (for example via the Thompson NFA construction). Here, we consider an alternative method based on Brzozowski <a href="">https://en.wikipedia.org/wiki/Brzozowski_derivative</a>. He introduced a symbolic method to construct an automata from a regular expression based on the concept of derivatives.</p>
<p>Given some expression r and a symbol x, we obtain the <em>derivative</em> of r w.r.t. x, written d(r,x), by taking way the leading symbol x from r.</p>
<p>In semantic terms, d(r,x) can be described as follows:</p>
<pre><code>L(d(r,x)) = x \ L(r)</code></pre>
<ul>
<li><p>x L(r) denotes the left quotient, i.e. the language <code>{ w | x . w in L(r)}</code>.</p>
<ul>
<li>We write <code>.</code> to denote concatenation. In some exposition this is left silent, i.e. <code>x w</code>.</li>
</ul></li>
<li><p>Hence, the derivative <code>d(r,x)</code> denotes the set of all words from L(R) where the leading symbol x has been removed.</p></li>
</ul>
<p>Thus, it is easy to solve the word problem. Let <code>w</code> be a word consisting of symbols <code>x1 . x2 .... xn-1 . xn</code>.</p>
<p>Compute</p>
<pre><code>d(r,x1) = r1
d(r1,x2) = r2
...
d(rn-1,xn) = rn</code></pre>
<p>That is, we repeatidely build the derivative of r w.r.t symbols xi.</p>
<p>Check if the final expression <code>rn</code> is nullable. An expression s is <em>nullable</em> if epsilon in L(s).</p>
<h3 id="formalizing-nullability-and-the-derivative-operation">Formalizing Nullability and the Derivative operation</h3>
<p>It is surprisingly simply to decide nullability by observing the structure of regular expression.</p>
<p>We write <code>n(r)</code> to denote the nullability test which yields a Boolean value (true/false).</p>
<pre><code>n(x) where xi is a symbol never holds.
n(epsilon) always holds.
n(phi) never holds.
n(r + s) holds iff n(r) holds or n(s) holds.
n(r . s) holds iff n(r) holds and n(s) holds.
n(r*) always holds.</code></pre>
<p>A similar approach (definition by structural recursion) works for the derivative operation.</p>
<p>We write <code>d(r,x)</code> to denote the derivative obtained by extracting the leading symbol <code>x</code> from expression <code>r</code>. For each derivative, we wish that the following holds: <code>L(d(r,x)) = x \ L(r)</code>.</p>
<p>As in case of the nullability test, the derivative operation is defined by observing the structure of regular expression patterns. Instead of a Boolean value, we yield another expression (the derivative).</p>
<pre><code>d(x,y) = either epsilon if x == y or phi otherwise
d(epsilon,y) = phi
d(phi,y) = phi
d(r + s, y) = d(r,y) + d(s,y)
d(r . s, y) = if n(r)
then d(r,y) . s + d(s,y)
else d(r,y) . s
d(r*, y) = d(r,y) . r*</code></pre>
<h2 id="examples">Examples</h2>
<p>Let's consider some examples to understand the workings of the derivative and nullability function.</p>
<p>We write <code>r -x-> d(r,x)</code> to denote application of the derivative on some expression <code>r</code> with respect to symbol <code>x</code>.</p>
<pre><code> x*
-x-> d(x*,x)
= d(x,x) . x*
= epsilon . x*
-x-> epsilon . x*
= d(epsilon,x) . x* + d(x*,x) -- n(epsilon) yields true
= phi . x* + epsilon . x*</code></pre>
<p>So repeated applicaton of the derivative on <code>x*$ for input string "x.x" yields</code>phi . x* + epsilon . x*`. Let's carry out the nullability function on the final expression.</p>
<pre><code> n(phi . x* + epsilon . x*)
= n(phi .x*) or n(epsilon . x*)
= (n(phi) and n(x*)) or (n(epsilon) and n(x*))
= (false and true) or (true and true)
= false or true
= true</code></pre>
<p>The final expression <code>phi . x* + epsilon . x*</code> is nullable. Hence, we can argue that expression <code>x*</code> matches the input word "x.x".</p>
<h2 id="implementation-in-go">Implementation in Go</h2>
<p>We make use of (extensible) interfaces to mimic pattern matching in Go.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">package</span> main
<span class="kw">import</span> <span class="st">"fmt"</span>
<span class="kw">type</span> RE <span class="kw">interface</span> {
deriv(<span class="dt">byte</span>) RE
nullable() <span class="dt">bool</span>
}
<span class="kw">type</span> Eps <span class="dt">int</span>
<span class="kw">type</span> Phi <span class="dt">int</span>
<span class="kw">type</span> Letter <span class="dt">byte</span>
<span class="kw">type</span> Kleene [<span class="dv">1</span>]RE
<span class="kw">type</span> Alt [<span class="dv">2</span>]RE
<span class="kw">type</span> Seq [<span class="dv">2</span>]RE
<span class="co">// test if regex is nullable</span>
<span class="kw">func</span> (r Eps) nullable() <span class="dt">bool</span> {
<span class="kw">return</span> <span class="ot">true</span>
}
<span class="kw">func</span> (r Phi) nullable() <span class="dt">bool</span> {
<span class="kw">return</span> <span class="ot">false</span>
}
<span class="kw">func</span> (r Letter) nullable() <span class="dt">bool</span> {
<span class="kw">return</span> <span class="ot">false</span>
}
<span class="kw">func</span> (r Kleene) nullable() <span class="dt">bool</span> {
<span class="kw">return</span> <span class="ot">true</span>
}
<span class="kw">func</span> (r Alt) nullable() <span class="dt">bool</span> {
<span class="kw">return</span> r[<span class="dv">0</span>].nullable() || r[<span class="dv">1</span>].nullable()
}
<span class="kw">func</span> (r Seq) nullable() <span class="dt">bool</span> {
<span class="kw">return</span> r[<span class="dv">0</span>].nullable() && r[<span class="dv">1</span>].nullable()
}
<span class="co">// build the derivative wrt x</span>
<span class="kw">func</span> (r Eps) deriv(x <span class="dt">byte</span>) RE {
<span class="kw">return</span> Phi(<span class="dv">1</span>)
}
<span class="kw">func</span> (r Phi) deriv(x <span class="dt">byte</span>) RE {
<span class="kw">return</span> Phi(<span class="dv">1</span>)
}
<span class="kw">func</span> (r Letter) deriv(x <span class="dt">byte</span>) RE {
y := (<span class="dt">byte</span>)(r)
<span class="kw">if</span> x == y {
<span class="kw">return</span> Eps(<span class="dv">1</span>)
} <span class="kw">else</span> {
<span class="kw">return</span> Phi(<span class="dv">1</span>)
}
}
<span class="kw">func</span> (r Kleene) deriv(x <span class="dt">byte</span>) RE {
<span class="kw">return</span> (Seq)([<span class="dv">2</span>]RE{r[<span class="dv">0</span>].deriv(x), r})
}
<span class="kw">func</span> (r Alt) deriv(x <span class="dt">byte</span>) RE {
<span class="kw">return</span> (Alt)([<span class="dv">2</span>]RE{r[<span class="dv">0</span>].deriv(x), r[<span class="dv">1</span>].deriv(x)})
}
<span class="kw">func</span> (r Seq) deriv(x <span class="dt">byte</span>) RE {
<span class="kw">if</span> r[<span class="dv">0</span>].nullable() {
<span class="kw">return</span> (Alt)([<span class="dv">2</span>]RE{(Seq)([<span class="dv">2</span>]RE{r[<span class="dv">0</span>].deriv(x), r[<span class="dv">1</span>]}), r[<span class="dv">1</span>].deriv(x)})
} <span class="kw">else</span> {
<span class="kw">return</span> (Seq)([<span class="dv">2</span>]RE{r[<span class="dv">0</span>].deriv(x), r[<span class="dv">1</span>]})
}
}
<span class="kw">func</span> testRegEx() {
<span class="kw">var</span> c Letter = Letter('c')
eps := (Eps)(<span class="dv">1</span>)
phi := (Phi)(<span class="dv">1</span>)
r1 := (Alt)([<span class="dv">2</span>]RE{eps, phi})
r2 := (Seq)([<span class="dv">2</span>]RE{c, r1})
fmt.Printf(<span class="st">"%b </span><span class="ch">\n</span><span class="st">"</span>, (r2.deriv('c')).nullable())
}
<span class="kw">func</span> main() {
testRegEx()
}</code></pre></div>
<h2 id="summary">Summary</h2>
<p>Each pattern matching function is method of the <code>RE</code> inferface.</p>
<p>Each case of the description of regular expression is represented by a specific type.</p>
<p>The methods of the <code>RE</code> inferface provide an implementation for each case.</p>
</div>
<div id="parser-combinators" class="slide section level1">
<h1>Parser combinators</h1>
<p>There are lots of different parsing approaches.</p>
<p>For example, see LL and LR parsing.</p>
<p>Another popular approach are <a href="Parser%20combinators">https://en.wikipedia.org/wiki/Parser_combinator</a>.</p>
<p>Main idea:</p>
<ul>
<li><p>Use combinators to build parsers.</p></li>
<li><p>Combinators are <em>fancy</em> API functions which hide much of the plumbing necessary to carry out parsing.</p></li>
<li><p>Often, a EBNF specification can be directly translated into some sequence of combinator calls.</p></li>
<li><p>There exists lots of parser combinator libraries for most programming languages.</p></li>
<li><p>Compared to parsing tools such as yacc and ANTLR, the parser is embedded into the host language. So, parser combinators form an <em>internal domaina-specific language (DSL)</em> (aka embedded DSL) whereas yacc and ANTLR are external DSLs.</p></li>
</ul>
<p>In the following, we give a (rather naive) encoding of a parser combinator library in Go.</p>
<h2 id="what-is-a-parser">What is a parser?</h2>
<p>A parser is a function which takes a string and yields a result and the remaining string.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">type</span> Parser <span class="kw">func</span>(s <span class="dt">string</span>) (<span class="kw">interface</span>{}, <span class="dt">string</span>, <span class="dt">bool</span>)</code></pre></div>
<p>where <code>interface{}</code> represents the parsing result (e.g. some abstract syntax tree) and the returning <code>string</code> represents the remaining input. As parsing may fail, we also return a Boolean value to represent either success or failure.</p>
<p>Application of a parser on some input.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> parse(f Parser, s <span class="dt">string</span>) (<span class="kw">interface</span>{}, <span class="dt">string</span>, <span class="dt">bool</span>) {
<span class="kw">return</span> f(s)
}</code></pre></div>
<h2 id="basic-combinators">Basic combinators</h2>
<p>The epsilon combinator which parses the empty string. We leave the input string untouched and report as a result the empty string.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> eps() Parser {
<span class="kw">return</span> <span class="kw">func</span>(s <span class="dt">string</span>) (<span class="kw">interface</span>{}, <span class="dt">string</span>, <span class="dt">bool</span>) {
<span class="kw">return</span> <span class="st">""</span>, s, <span class="ot">true</span>
}
}</code></pre></div>
<p>A parser to accept a specific character (item).</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> item(x <span class="dt">byte</span>) Parser {
<span class="kw">return</span> <span class="kw">func</span>(s <span class="dt">string</span>) (<span class="kw">interface</span>{}, <span class="dt">string</span>, <span class="dt">bool</span>) {
<span class="kw">if</span> <span class="fu">len</span>(s) == <span class="dv">0</span> {
<span class="kw">return</span> <span class="dv">0</span>, s, <span class="ot">false</span>
} <span class="kw">else</span> <span class="kw">if</span> s[<span class="dv">0</span>] == x {
<span class="kw">return</span> s[<span class="dv">0</span>], s[<span class="dv">1</span>:<span class="fu">len</span>(s)], <span class="ot">true</span>
} <span class="kw">else</span> {
<span class="kw">return</span> <span class="dv">0</span>, s, <span class="ot">false</span>
}
}
}</code></pre></div>
<h2 id="building-higher-order-combinators">Building higher-order combinators</h2>
<p>Build a new parser by composition of an exisisting parser.</p>
<div class="sourceCode"><pre class="sourceCode go"><code class="sourceCode go"><span class="kw">func</span> (p1 Parser) alt(p2 Parser) Parser {
<span class="kw">return</span> <span class="kw">func</span>(s <span class="dt">string</span>) (<span class="kw">interface</span>{}, <span class="dt">string</span>, <span class="dt">bool</span>) {
v, rest, o := parse(p1, s)
<span class="kw">if</span> !o {
<span class="kw">return</span> parse(p2, s)
} <span class="kw">else</span> {
<span class="kw">return</span> v, rest, o
}
}
}
<span class="kw">func</span> (p1 Parser) seq(p2 <span class="kw">func</span>(<span class="kw">interface</span>{}) Parser) Parser {
<span class="kw">return</span> <span class="kw">func</span>(s <span class="dt">string</span>) (<span class="kw">interface</span>{}, <span class="dt">string</span>, <span class="dt">bool</span>) {
v, rest, o := parse(p1, s)
<span class="kw">if</span> !o {
<span class="kw">return</span> v, rest, o
} <span class="kw">else</span> {
<span class="kw">return</span> parse(p2(v), rest)
}
}
}
<span class="kw">func</span> (p1 Parser) conc(p2 Parser) Parser {
<span class="kw">return</span> p1.seq(<span class="kw">func</span>(v <span class="kw">interface</span>{}) Parser { <span class="kw">return</span> p2 })
}</code></pre></div>