-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1290 lines (1034 loc) · 57.6 KB
/
index.html
File metadata and controls
1290 lines (1034 loc) · 57.6 KB
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 name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title></title>
<link rel="stylesheet" href="dist/reset.css">
<link rel="stylesheet" href="dist/reveal.css" />
<link rel="stylesheet" href="css/slides-extended.css" />
<link rel="stylesheet" href="dist/theme/sky.css" id="theme" />
<link rel="stylesheet" href="plugin/highlight/vs2015.css" />
<link rel="stylesheet" href="plugin/customcontrols/style.css">
<script defer src="dist/fontawesome/all.min.js"></script>
<script type="text/javascript">
function pageInIframe() {
return (window.location !== window.parent.location);
}
let forgetPop = true;
function onPopState(event) {
if(forgetPop){
forgetPop = false;
} else if( pageInIframe()) {
parent.postMessage(event.target.location.href, "app://obsidian.md");
}
}
window.onpopstate = onPopState;
window.onmessage = event => {
if(event.data == "reload"){
window.document.location.reload();
}
forgetPop = true;
}
function fitElements() {
const itemsToFit = document.getElementsByClassName('fitText');
for (const item in itemsToFit) {
if (Object.hasOwnProperty.call(itemsToFit, item)) {
const element = itemsToFit[item];
fitElement(element, 1, 1000);
element.classList.remove('fitText');
}
}
}
function fitElement(element, start, end) {
let size = (end + start) / 2;
element.style.fontSize = `${size}px`;
if (Math.abs(start - end) < 1) {
while (element.scrollHeight > element.offsetHeight) {
size--;
element.style.fontSize = `${size}px`;
}
return;
}
if (element.scrollHeight > element.offsetHeight) {
fitElement(element, start, size);
} else {
fitElement(element, size, end);
}
}
document.onreadystatechange = () => {
fitElements();
if (document.readyState === 'complete') {
if (pageInIframe() && window.location.href.indexOf("?export") != -1){
parent.postMessage(event.target.location.href, "app://obsidian.md");
}
if (window.location.href.indexOf("print-pdf") != -1){
let stateCheck = setInterval(() => {
clearInterval(stateCheck);
window.print();
}, 250);
}
}
};
</script>
</head>
<body>
<div class="reveal">
<div class="slides"><section data-markdown><script type="text/template"><!-- .slide: class="drop" data-background-image="./title.jpg" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
### Что такое функциональное программирование?
<img src="what-is-fp-question.jpg" alt="" style="width: 960×540px; object-fit: fill">
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
Функциональное программирование — это набор выражений, который нужно каким-то образом интерпретировать
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
### Установки функциональных языков
- Ссылочная прозрачность
- Неизменяемые данные
- Expressions вместо statements
- Данные и функции отдельно
- Композиция
- Контроль эффектов
- Статическая типизация
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
### Ссылочная прозрачность
Замена одного выражения другим без какого-либо изменения результата
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Императивная программа
```php [|1,5,9|3,7,10|2,6,14]
function lhs(): int {
log('lhs() call');
return 1;
}
function rhs(): int {
log('rhs() call');
return 41;
}
function app(): int {
return lhs() + rhs();
}
$result = app();
log($result);
```
```txt
[log]: lhs() call
[log]: rhs() call
[log]: 42
```
<!-- .element: class="fragment" -->
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Подстановка результата операций может менять смысл
```php
function app(): int {
return 1 + 41;
}
log(app())
```
```txt
[log]: calculate
[log]: 42
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
Результат функции с побочными эффектами невозможно инлайнить
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Ссылочно прозрачная альтернатива
```php [|2,5|9|10|11]
function lhs(): Expr<int> {
return Expr::log('call lhs()')->map(fn() => 1);
}
function rhs(): Expr<int> {
return Expr::log('call rhs()')->map(fn() => 41);
}
function app(): Expr<int> {
return Exp::scope()
->bind(a: lhs(), b: rhs())
->map(fn($i) => $i->a + $i->b);
}
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Запуск программы (на краю света)
```php []
unsafeRun(
expr: app()->flatMap(Expr::log(...)),
interpreter: new ExprInterpreter(),
);
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Возможность инлайнить результат функции
```php []
$app = Expr::scope()
->bind(
a: Expr::log('call lhs()')->map(fn() => 1),
b: Expr::log('call rhs()')->map(fn() => 41),
)
->map(fn($i) => $i->a + $i->b)
->flatMap(Expr::log(...))
unsafeRun($app, new ExprInterpreter());
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
### Неизменяемые данные
Все данные заморожены 🥶
Они никогда не будут изменены!
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
В PHP это не по умолчанию
*И без гарантий на неизменяемость...*
<!-- .element: class="fragment" -->
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Однажды создан и не может быть изменен ✅
```php
final readonly class Person
{
public function __construct(
public int $id,
public string $name,
) {}
}
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Изменяемый класс❗️
```php
final class Address
{
public function __construct(
public string $street,
) {}
}
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Могут быть ссылки на изменяемые объекты
```php [6]
final readonly class Person
{
public function __construct(
public int $id,
public string $name,
public Address $address,
) {}
}
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
С readonly в PHP есть более неприятный момент
*Это копирование readonly объектов...*
<!-- .element: class="fragment" -->
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Это не будет работать ❌
```php
final readonly class Person
{
public function __construct(
public int $id,
public string $name,
) {}
}
$a = new Person(id: 42, name: 'test');
$b = clone $a;
$b->name = 'NewName';
// Error: Cannot modify readonly property Person::$name
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### "Рабочий" вариант на текущий момент
```php [|10]
final readonly class Person
{
public function __construct(
public int $id,
public string $name,
) {}
}
$a = new Person(id: 42, name: 'test');
$b = new Person(id: $a->id, name: 'newName');
```
*Копируем все свойства вручную...*
<!-- .element: class="fragment" -->
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
Есть пару rfc которые могут это исправить
https://wiki.php.net/rfc/clone_with
https://wiki.php.net/rfc/records
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Пустяки на бесконечном пути бытия
<img src="immutable-ds.gif" alt="" style="object-fit: scale-down">
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Отсутвие незменяемых структур данных
- Нет в PHP core
- Нет библиотек
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Простой неизменяемый список
```scala 3 []
enum Lst[+A]:
case Cons(head: A, tail: Lst[A]) extends Lst[A]
case Nil extends Lst[Nothing]
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Все версии списка доступны
```scala 3
val v1 = Lst.Cons(1, Lst.Nil) // [1]
val v2 = Lst.Cons(2, v1) // [1, 2]
val v3 = Lst.Cons(3, v2) // [1, 2, 3]
val v4 = Lst.Cons(4, v3) // [1, 2, 3, 4]
val v5 = Lst.Cons(5, v4) // [1, 2, 3, 4, 5]
val v6 = Lst.Cons(6, v5) // [1, 2, 3, 4, 5, 6]
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Давайте сделаем это на php
[Вот в javascript есть](https://github.com/immutable-js/immutable-js)
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
PHP погибает с segfult при глубогой вложенности объектов 🤡
<img src="lol-segfault.gif" alt="" style="width: 640px; height: 420px; object-fit: fill">
https://github.com/php/doc-en/issues/1228
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
### Циклы и ветвления забанены
<img src="no-more-statements.jpg" alt="" style="object-fit: scale-down">
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Старые друзья VS новые
- for/while/continue/break - рекурсия
- if/else/switch - pattern matching
- return - просто не нужен
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Ну как там с рекурсией?
<img src="recursion-question.jpeg" alt="" style="width: 640px; height: 420px; object-fit: fill">
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
```php [|2-3|4]
function sum(list<int> $nums): int {
return $nums === []
? 0
: $nums[0] + sum(array_slice($nums, offset: 1));
}
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Причины из-за которых рекурсия это больно
- Stack-frame на каждый рекурсивный вызов
- Жалобы xdebug на большую вложенность
- Segfault (если вам очень сильно повезет)
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Хвостовая рекурсия
Частный случай рекурсии, при котором рекурсивный вызов является последней операцией перед возвратом из функции
*Оптимизируется в цикл*
<!-- .element: class="fragment" -->
*Не реализованно в PHP*
<!-- .element: class="fragment" -->
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Пример хвостовой рекурсии
```scala 3 [|1|3|4-5|6|2|8]
def sum(nums: List[Int]): Int =
@tailrec
def loop(nums: List[Int], acc: Int = 0): Int =
if nums.isEmpty
then acc
else loop(nums.tail, acc + nums.head)
loop(nums)
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Свертка
Если у вас получается сделать хвостовую рекурсию, то получится сделать свертку
```php [|3|4|6]
function sum(list<int> $nums): int
{
$initial = 0;
$reducer = fn (int $sum, int $num) => $sum + $num;
return array_reduce($nums, $reducer, $initial);
}
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Взаимная рекурсия
```php []
function even(int $i): bool
{
return $i === 0
? true
: odd($i - 1);
}
function odd(int $i): bool
{
return $i === 0
? false
: even($i - 1);
}
var_dump(even(1)); // false
var_dump(even(2)); // true
var_dump(even(666_666_666)); // Out of memory
```
https://3v4l.org/lCOerV#v8.3.13
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Trampoline
Если не удается сделать хвостовую рекурсию
```php
function evenT(int $i): Trampoline<bool> {
return $i === 0
? new Done(true)
: new Cont(fn() => oddT($i - 1));
}
function oddT(int $i): Trampoline<bool> {
return $i === 0
? new Done(false)
: new Cont(fn() => evenT($i - 1));
}
var_dump(runTrampoline(evenT(1))); // false
var_dump(runTrampoline(evenT(2))); // true
var_dump(runTrampoline(evenT(666_666_666))); // true
```
https://3v4l.org/aev4d#v8.3.13
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Pattern matching for poor PHP programmers
```php [|3|4|5-8]
function loop(list<int> $nums, int $acc = 0): int
{
return match (true) {
$nums === [] => $acc,
$nums !== [] => loop(
nums: array_slice($nums, offset: 1),
acc: $acc + $nums[0],
),
};
}
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
Как выглядит богатый pattern matching
```scala 3 [|4|5|6]
def sum(nums: List[Int]): BigInt =
@tailrec
def loop(nums: List[Int], acc: Int = 0): int =
nums match {
case Nil => acc
case head :: tail => loop(tail, acc + head)
}
loop(nums)
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Ожидаем похожее в PHP
<img src="wait-for-patmat.gif" alt="" style="object-fit: scale-down">
https://wiki.php.net/rfc/pattern-matching
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
### Функции как значения
- Передавать функции в другие функции
- Возвращать функции из функций
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Было всегда (или почти)
```php []
$intToString = function (int $a) {
return (string) $a;
};
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Появилось с PHP 7.4
```php []
$intToString = fn (int $a) => (string) $a;
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Появилось аж с PHP 8.1
```php
function intToString(int $a): string
{
return (string) $a;
}
$intToString = intToString(...);
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
Все текущие стат анализаторы лагают в области анонимных функций 🥲
<img src="sa-sucks.jpg" alt="" style="object-fit: scale-down">
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Что может быть проще ?
```php []
function identity<A>(A $value): A
{
return $value;
}
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Чуть сложнее, но все еще просто
```php []
function simple((int => int) $intToInt): int
{
return $intToInt(42);
}
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### "Слишком сложно"
```php [|1-2|4-5|7-8]
// PHPStan выводит тип Closure<A>(A): A
$id = identity(...);
// Но не может понять, что $fn можно передать сюда
simple($id);
// А так можно 🤡
simple(fn($i) => $i);
```
https://phpstan.org/r/0a262bfb-ade5-4303-b03a-ac0521634b5e
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
### Композиция функций
Если функции являются значениями, то эти значения можно комбинировать друг с другом
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Комбинировать их можно в двух стилях
- Data-first
- Data-last
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Только унарные функции
<img src="only-unary-functions.gif" alt="" style="width: 640px; height: 420px; object-fit: fill">
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Data first
- Передаем изначальные данные
- Вычисляем слева направо
```php [|6|7|8]
$addOne = fn(int $a) => $a + 1;
$intToString = fn(int $a) => (string) $a;
// "42"
$result = pipe(
41,
$addOne,
$intToString
);
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Data last
- Передаем функции для выполнения слева направо
- Результатом будет композиция функций
```php [|5|8]
$addOne = fn(int $a) => $a + 1;
$intToString = fn(int $a) => (string) $a;
// Closure(int): string
$addOneAndIntToString = compose($addOne, $intToString);
// "42"
$result = $addOneAndIntToString(41);
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Невозможно объявить именованую функцию
```php []
// Так не можем:
const addOneAndToString1 = compose(
addOne(...),
intToString(...),
);
// И так не можем:
function addOneAndToString2 = compose(
addOne(...),
intToString(...),
);
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Можем ли мы сделать такие функции в PHP?
- С точки зрения php - да ✅
- C точки зрения стат анализа - нет 🥲
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Элементарная функция с невыразимой сигнатурой
```php
/**
* Что здесь написать ? 🗿🗿🗿
*/
function pipe(mixed $value, callable ...$transformations)
{
$result = $value;
foreach ($transformations as $transformation) {
$result = $transformation($result);
}
return $result;
}
```
*Тоже касается и функции compose...*
<!-- .element: class="fragment" -->
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
Хотели добавить pipe operator в PHP
https://wiki.php.net/rfc/pipe-operator-v2
Но слишком много голосов было против 🥲
Ждем pipe-operator-v3?
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Проверки на null мешают композиции
<img src="iferrneqerr.webp" alt="" style="object-fit: scale-down">
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
```php [|1|3-4|5-9]
$num = getNullableInt();
return $num === null
? null
: pipe(
$num,
addOne(...),
intToString(...),
);
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
```php []
return pipe(
getNullableInt(),
addOne(...),
intToString(...),
);
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Украдем `Option[A]` к себе в `PHP`
```scala 3 [|2|3|5-6|8-9]
enum Option[+A]:
case Some(value: A) extends Option[A]
case None extends Option[Nothing]
// Значение определено
val fortyTwo = Option.Some(42)
// Значение неопределено
val none = Option.None
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Украли, но все не получилось
```php [|1-2|4-11|13-14]
/** @template-covariant A */
interface Option {}
/**
* @template-covariant A
* @implements Option<A>
*/
final readonly class Some implements Option {
/** @param A $some */
public function __construct(public mixed $some) {}
}
/** @implements Option<never> */
enum None implements Option { case instance; }
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Сможем украсть полностью после этого `RFC`
https://wiki.php.net/rfc/tagged_unions
*Добаввить мем про кражу уровень 100*
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
Функции которые будут возвращать `Option<A>` легко композировать
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
`Option<int>`
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
`(int -> string)`
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
`(Option<int> -> Option<string>)`
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Та самая функция
```php [|7|9|10|11|12]
/**
* @template A
* @template B
* @param callable(A): B $ab
* @return callable(Option<A>): Option<B>
*/
function map(callable $ab): callable
{
return static fn (Option $fa) =>
isSome($fa)
? new Some($ab($fa->some))
: None::instance;
}
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Попробуем
```php [|1-2|5-9|6|7|8|]
/** @var Option<int> */
$num = getOptionInt();
// Option<string>
$result = pipe(
$num,
Option\map(addOne(...)),
Option\map(intToString(...)),
);
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
`Option<string>`
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
`(string -> Option<int>)`
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
`(Option<string> -> Option<int>)`
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Та самая функция
```php [|7|9|10|11]
/**
* @template A
* @template B
* @param callable(A): Option<B> $ab
* @return callable(Option<A>): Option<B>
*/
function flatMap(callable $ab): callable
{
return static fn (Option $fa) =>
isSome($fa)
? $ab($fa->some)
: None::instance;
}
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
#### Какой-то command handler
```php [|8|9|4,10]
final readonly class CreateProjectInviteHandler
{
/**
* @return Option<ProjectInvite>
*/
#[Handler]
public function __invoke(
CreateProjectInvite $command,
MessageBus $bus,
): Option {...}
}
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
```php [|1|3-4|7|9-11|13]
$user = $bus(new FindUser($command->userId));
if ($user === null) {
return null;
}
$project = $bus(new FindProject($command->projectId));
if ($project === null) {
return null;
}
return new ProjectInvite($user, $project);
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
Найдем `Project` затем `User` и создадим `ProjectInvite`
```php [|2|3|4|5|5-8]
return pipe(
$bus(new FindUser($command->userId)),
Option\flatMap(fn($user) => pipe(
$bus(new FindProject($command->projectId)),
Option\map(fn($project) => new ProjectInvite(
user: $user,
project: $project,
)),
)),
);
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
`Project` зависит от `User`
Из-за этого появляется вложенность.
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
Нам нужна do-notation
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
Как выглядит do-notation в Scala
```scala 3 [|3-6|4|5|6]
final class CreateProjectInviteHandler:
def handle(msg: CreateProjectInvite, bus: MessageBus) =
for
user <- bus(GetUser(msg.userId))
project <- bus(GetProject(msg.projectId))
yield ProjectInvite(user, project)
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">
Все это syntax-sugar для такой конструкции
```scala 3
bus(GetUser(msg.userId))
.flatMap(user =>
bus(GetProject(message.projectId))
.map(project =>
ProjectInvite(user, project)
)
)
```
</div></script></section><section data-markdown><script type="text/template"><!-- .slide: class="drop" template="" -->
<div class="" style="position: absolute; left: 0px; top: 0px; height: 900px; width: 960px; min-height: 900px; display: flex; flex-direction: column; align-items: center; justify-content: center" absolute="true">