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
|
---
#theme: seriph
canvasWidth: 750
title: Really Functional Data Structures
author: Marvin Borner
colorSchema: light
class: text-center
transition: instant
mdc: true
# take snapshot for each slide in the overview
# overviewSnapshots: true
---
# *Really* Functional<br>Data Structures
[Marvin Borner](https://marvinborner.de)
<!--
Datenstrukturen nur aus Funktionen! Und wie man mit ihnen umgeht!
Frage: Erfahrung mit Lambdakalkül und Datenstrukturen?
Wieso, weshalb???
-->
---
# Goal/Motivation
<v-clicks>
- Represent arbitrary data using only functions
- No classes, structs, numbers, etc.
- Basically pure lambda calculus
- Think/program more functionally
- Elegant and minimal solutions
- Useful for theorem proving?
- Really fun!
</v-clicks>
<!--
- ..
- übertragbar
- e.g. easily typable
- ..
-->
---
# Anonymous Functions (Lambdas)
- Functions (abstractions) have an argument and a body
- Applying a function with an argument substitutes it
- Functions can be assigned to names (easier to read)
---
## JavaScript Notation
```js {monaco-run} {showOutputAt:1}
f = x => x + 42
console.log(f(2))
```
<div v-click=2>
```js {monaco-run} {showOutputAt:3}
f = x => y => x + y
console.log(f(2)(42))
```
</div>
---
# Really Functional Data Structures
<v-clicks>
- Only use pure, closed terms
- Multiple states are encoded via (unapplied) arguments and applications
- Carefully, such that data doesn't reduce itself!
- State can often be extracted using "selector" argument
</v-clicks>
<!--
Wie Daten rein funktional darstellen?
-->
---
layout: cover
---
# Common
---
# Boolean Logic
- **Capacity**: 1 Bit (true/false)
- **Operations**: and/not/etc.
<!--
mit was einfachem starten :)
-->
---
## Church Booleans
```js
tru = t => f => t
fls = t => f => f
```
---
## Church Booleans
```js {monaco-run} {showOutputAt:'+1'}
tru = t => f => t
fls = t => f => f
evalBool = bool => bool("true")("false")
console.log(evalBool(tru))
console.log(evalBool(fls))
```
---
## Example: Negation
<v-clicks>
- We know: `bool = t => f => t/f`
- If `bool = t => f => t`, then `!bool = t => f => f`
- If `bool = t => f => f`, then `!bool = t => f => t`
- Therefore:
``` js
negate = bool => t => f => bool(f)(t)
// ^ ^
// one will be eliminated!
```
</v-clicks>
---
## Example: Negation
```js {monaco-run} {showOutputAt:'+1'}
tru = t => f => t
fls = t => f => f
negate = bool => t => f => bool(f)(t)
evalBool = bool => bool("true")("false")
console.log(evalBool(negate(tru)))
console.log(evalBool(negate(fls)))
```
---
## Other Operators
- ``` js
and = a => b => b(a)(b)
```
- ``` js
xor = a => b => b(a(fls)(b))(a)
```
- ``` js
xnor = a => b => b(a)(a(b)(tru))
```
- ``` js
impl = a => b => a(b)(tru)
```
- ...
---
# Church Pairs
<v-clicks>
- Stores two values
- The selector function gets applied to both values:
``` js
examplePair = s => s(A)(B)
```
</v-clicks>
---
## Construction/Selection
```js {monaco-run} {showOutputAt:'+1'}
cons = a => b => s => s(a)(b)
car = pair => pair(a => b => a)
cdr = pair => pair(a => b => b)
// ^^^^^^^^^^^
// selector function
examplePair = cons("a")("b")
console.log(car(examplePair))
console.log(cdr(examplePair))
```
---
layout: cover
---
# Lists
---
# Church Lists
<v-clicks depth=2>
- Idea: A list is just a composition of pairs:<br>`[A, B, C, D] = (A, (B, (C, (D, NIL))))`
- But what is `NIL`?
- marks the end of the list
- differentiable from other elements
</v-clicks>
---
## `isNil`?
- We define NIL such that it *ignores* its selector argument
```js
cons = a => b => s => s(a)(b)
nil = s => x => x
exampleList = cons("a")(cons("b")(cons("c")(nil)))
// = s1 => s1("a")(s2 => s2("b")(s3 => s3("c")(nil)))
```
---
## `isNil`?
- We define NIL such that it *ignores* its selector argument
```js {monaco-run} {showOutputAt:'+1'}
cons = a => b => s => s(a)(b)
nil = s => x => x
exampleList = cons("a")(cons("b")(cons("c")(nil)))
// = s1 => s1("a")(s2 => s2("b")(s3 => s3("c")(nil)))
isNil = list => list(head => tail => right => fls)(tru)
// ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^
// cons/nil pair selector nil selector
console.log(evalBool(isNil(nil)))
console.log(evalBool(isNil(exampleList)))
```
---
## Example: Iteration
```js {monaco-run} {showOutputAt:'+1'}
y = f => x => f(y(f))(x)
exampleList = cons("a")(cons("b")(cons("c")(nil)))
length = y(rec => n => list => isNil(list)
(() => n)
(() => rec(n + 1)(cdr(list))()))
(0)
console.log(length(exampleList)())
```
---
# Other Lists
Example: Encoding of `["a", "b"]`
<v-clicks>
- Parigot:
```js
end => s1 => s2("a")(s2 => s2("b")(end))
```
- Scott:
```js
s1 => end1 => s1("a")(s2 => end2 => s2("b")(s3 => end3 => end3))
```
- $n$-Tuple:
```js
s => s("a")("b")...
```
</v-clicks>
<!--
Parigot: Triviales append
Scott: Kein wirklicher Sinn
n-Tupel: Vorteile siehe später, length/pop schwierig/unmöglich
-->
---
layout: cover
---
# Numbers
(brief overview)
---
# Church Numerals
- Idea: Represent a number $n$ by applying $n$ composed functions to some argument!
---
# Church Numerals
- Idea: Represent a number $n$ by applying $n$ composed functions to some argument!
- For example:
```js {monaco-run} {showOutputAt:'+1'}
three = s => z => s(s(s(z)))
evalChurch = n => n(x => x + 1)(0)
console.log(evalChurch(three))
```
---
## Successor
- Add another `s` to the composition
- We also need to "rebind" existing `s` and `z`!
---
## Successor
- Add another `s` to the composition
- We also need to "rebind" existing `s` and `z`!
```js {monaco-run} {showOutputAt:'+1'}
// three = s => z => s(s(s(z)))
zero = s => z => z
succ = n => s => z => s(n(s)(z))
console.log(evalChurch(succ(succ(succ(zero)))))
```
<!--
Predecessor really hard :(
-->
---
## `isZero`?
Similar to `isNil`!
```js {monaco-run} {showOutputAt:'+1'}
// three = s => z => s(s(s(z)))
isZero = n => n(z => fls)(tru)
console.log(evalBool(isZero(zero)))
console.log(evalBool(isZero(succ(zero))))
```
---
# Other Numeral Systems
Example: Encoding of $3$
<v-clicks>
- Scott:
```js
s1 => z1 => s1(s2 => z2 => s2(s3 => z3 => s3(s4 => z4 => z4)))
```
- Parigot:
```js
end => s1 => s1(s2 => s2(s3 => s3(s4 => end)))
```
- Mogensen:
```js
end => b1 => b0 => b1(b1(end)) // binary
end => tn => tp => t0 => t0(tp(end)) // balanced ternary
```
- Wadsworth, de Bruijn, Rationals, ...
</v-clicks>
<!--
Scott: Trivial pred, add komplexer
Parigot: pred/add beide in einem Schritt!
-->
---
layout: cover
---
# Algebraic Types
<!--
Wie man diese speichern kann
Typen haben wir natürlich nicht
-->
---
# Products/Records
- Stores multiple elements, supports construction and extraction
- For two elements: Just a Church pair
- For multiple elements: Extend the pair!
---
# Products/Records
- Stores multiple elements, supports construction and extraction
- For two elements: Just a Church pair
- For multiple elements: Extend the pair!
```js {monaco-run} {showOutputAt:'+1'}
// data Friends = Friends { best :: String, friendly :: String, weird :: String }
Friends = best => friendly => weird => s => s(best)(friendly)(weird)
best = friends => friends(best => _ => _ => best)
friendly = friends => friends(_ => friendly => _ => friendly)
weird = friends => friends(_ => _ => weird => weird)
friends = Friends("Alice")("Bob")("Carol")
console.log(best(friends))
```
---
# Sums/Unions
- Similar: Stores multiple *types*, but only one at a time
- Typical functional data structure (e.g. Haskell's `data` "|")
<!--
Selektion/etc. sehr ähnlich zu Produkttypen, nur mit *mehr* Selektoren!
-->
---
```js {monaco-run}
// data Tree = Leaf Int | Node Tree Tree
Leaf = n => leaf => node => leaf(n)
Node = a => b => leaf => node => node(a)(b)
nodeLeft = node => node(_ => _)(a => b => a)
nodeRight = node => node(_ => _)(a => b => b)
leafValue = leaf => leaf(n => n)(_ => _)
isLeaf = tree => tree(n => tru)(a => b => fls)
isNode = tree => tree(n => fls)(a => b => tru)
```
---
```js {monaco-run}
// data Tree = Leaf Int | Node Tree Tree
Leaf = n => leaf => node => leaf(n)
Node = a => b => leaf => node => node(a)(b)
nodeLeft = node => node(_ => _)(a => b => a)
nodeRight = node => node(_ => _)(a => b => b)
leafValue = leaf => leaf(n => n)(_ => _)
isLeaf = tree => tree(n => tru)(a => b => fls)
isNode = tree => tree(n => fls)(a => b => tru)
exampleTree = Node(Leaf(1))(Node(Leaf(2))(Leaf(3)))
console.log(evalBool(isNode(exampleTree)))
console.log(evalBool(isLeaf(nodeLeft(exampleTree))))
console.log(leafValue(nodeLeft(exampleTree)))
console.log(leafValue(nodeRight(nodeRight(exampleTree))))
```
---
layout: cover
---
# Trees
Trivial with presented data structures
- Rose trees
- Binary trees
- Finger trees
- Balanced trees
---
layout: cover
---
# Monads
---
# Maybe
Stores either nothing or a value, but *tagged*
```js {monaco-run} {showOutputAt:'+1'}
// data Maybe a = Nothing | Just a
Nothing = nothing => just => nothing
Just = v => nothing => just => just(v)
// instance Monad
pure = Just
bind = mx => f => mx(mx)(f)
// ------------^^ ^-----------------
// case Nothing case Just (apply)
evalMaybe = maybe => maybe("Nothing")(v => "Just " + v)
console.log(evalMaybe(bind(Nothing)(n => pure(n + 1))))
console.log(evalMaybe(bind(Just(42))(n => pure(n + 1))))
```
<!--
Basically just a tagged union... boring
-->
---
# Either
Stores either a value or another value, but *tagged*
```js {monaco-run} {showOutputAt:'+1'}
// data Either a b = Left a | Right b
Left = a => left => right => left(a)
Right = b => left => right => right(b)
// instance Monad
pure = Right
bind = mx => f => mx(Left)(f)
// ---------^^^^ ^------------------
// case Left case Right (apply)
evalEither = either => either(a => "Left " + a)(b => "Right " + b)
console.log(evalEither(bind(Left(42))(n => pure(n + 1))))
console.log(evalEither(bind(Right(42))(n => pure(n + 1))))
```
---
layout: cover
---
# Meta
(little detour)
---
# Mogensen-Scott
- Meta encoding of lambda terms
- Tagged union: `Symbol x | Application Term Term | Lambda Term`
- Translation:
```js
enc[x] = sym => app => lam => sym(x)
enc[f(x)] = sym => app => lam => app(enc[f])(enc[x])
enc[x => m] = sym => app => lam => lam(x => enc[m])
```
---
## Meta-Circular Interpreter
Evaluate lambda terms using the lambda implementation of the language itself!
```js
enc[x] = sym => app => lam => sym(x)
enc[f(x)] = sym => app => lam => app(enc[f])(enc[x])
enc[x => m] = sym => app => lam => lam(x => enc[m])
```
```js
eval = term => term
(x => x)
(f => x => eval(f)(eval(x)))
(m => x => eval(m(x)))
```
---
# de Bruijn-Church
- Idea: Encode symbols as Church-encoded de Bruijn indices
- Abstractions are simpler and allow open terms
- Translation:
```js
enc[i] = idx => app => lam => church[idx]
enc[f(x)] = idx => app => lam => app(enc[f])(enc[x])
enc[b] = idx => app => lam => lam(enc[b])
```
---
## 194 bit self interpreter
Minimal data structures allow minimal interpreters!
<style>
pre, code, pre * {
color: black !important;
background-color: transparent !important;
margin: 0 auto;
width: min-content;
font-size: 90%;
line-height: 1.1 !important;
}
small {
font-size: 50%;
}
</style>
```
01010001 00011100
11010000 ###### 11100110
10000 ############ 00001
01011 ##### ##### 00001
11100 #### #### 00101
01110 #### ##### 00011
00000 #### ###### 10100
00011 #### ### #### 00111
10000 #### ## #### 11111
00001 #### ### #### 11110
00010 ###### #### 11110
10011 ##### #### 10100
11110 #### #### 00011
11000 ##### ##### 00011
11000 ############ 01011
01101110 ###### 00011001
00011010 00011010
```
<small>
See [Metaprogramming and Self-Interpretation](https://text.marvinborner.de/2023-09-03-21.html)
</small>
<!--
Learning: minimale Datenstrukturen können zu minimalem Code führen!
-->
---
layout: cover
class: text-left
---
# Other Data?
- Strings? List of 2-ary numerals.
- Bits? List of Church booleans.
- Maps? Balanced tree with Church pairs.
---
layout: cover
---
# Images
---
# Quad Trees
- Leafs/pixels:
```js
black = w => b => b
white = w => b => w
```
- 4-tuple (product type):
```js
screen = s => s(TL)(TR)(BL)(BR)
```
- Where `TL`,`TR`,`BL`,`BR` are either a screen or a pixel
---
layout: cover
---
# Demo
[Lambda Screen](https://lambda-screen.marvinborner.de)
|