git.iko.soy/ikoHSE/sc-lectures
on dependabot/npm_and_yarn/reveal.js/express-4.17.3 help sign in
654 lines 35 kB history raw
1<!DOCTYPE html>
2<html>
3<head>
4 <meta charset="utf-8">
5 <meta name="generator" content="pandoc">
6 <meta name="author" content="Ilya Kostyuchenko">
7 <title>1</title>
8 <meta name="apple-mobile-web-app-capable" content="yes">
9 <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
10 <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
11 <link rel="stylesheet" href="reveal.js/css/reset.css">
12 <link rel="stylesheet" href="reveal.js/css/reveal.css">
13 <style>
14 code{white-space: pre-wrap;}
15 span.smallcaps{font-variant: small-caps;}
16 span.underline{text-decoration: underline;}
17 div.column{display: inline-block; vertical-align: top; width: 50%;}
18 div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
19 ul.task-list{list-style: none;}
20 pre > code.sourceCode { white-space: pre; position: relative; }
21 pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
22 pre > code.sourceCode > span:empty { height: 1.2em; }
23 code.sourceCode > span { color: inherit; text-decoration: inherit; }
24 div.sourceCode { margin: 1em 0; }
25 pre.sourceCode { margin: 0; }
26 @media screen {
27 div.sourceCode { overflow: auto; }
28 }
29 @media print {
30 pre > code.sourceCode { white-space: pre-wrap; }
31 pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
32 }
33 pre.numberSource code
34 { counter-reset: source-line 0; }
35 pre.numberSource code > span
36 { position: relative; left: -4em; counter-increment: source-line; }
37 pre.numberSource code > span > a:first-child::before
38 { content: counter(source-line);
39 position: relative; left: -1em; text-align: right; vertical-align: baseline;
40 border: none; display: inline-block;
41 -webkit-touch-callout: none; -webkit-user-select: none;
42 -khtml-user-select: none; -moz-user-select: none;
43 -ms-user-select: none; user-select: none;
44 padding: 0 4px; width: 4em;
45 background-color: #232629;
46 color: #7a7c7d;
47 }
48 pre.numberSource { margin-left: 3em; border-left: 1px solid #7a7c7d; padding-left: 4px; }
49 div.sourceCode
50 { color: #cfcfc2; background-color: #232629; }
51 @media screen {
52 pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
53 }
54 code span. { color: #cfcfc2; } /* Normal */
55 code span.al { color: #95da4c; background-color: #4d1f24; font-weight: bold; } /* Alert */
56 code span.an { color: #3f8058; } /* Annotation */
57 code span.at { color: #2980b9; } /* Attribute */
58 code span.bn { color: #f67400; } /* BaseN */
59 code span.bu { color: #7f8c8d; } /* BuiltIn */
60 code span.cf { color: #fdbc4b; font-weight: bold; } /* ControlFlow */
61 code span.ch { color: #3daee9; } /* Char */
62 code span.cn { color: #27aeae; font-weight: bold; } /* Constant */
63 code span.co { color: #7a7c7d; } /* Comment */
64 code span.cv { color: #7f8c8d; } /* CommentVar */
65 code span.do { color: #a43340; } /* Documentation */
66 code span.dt { color: #2980b9; } /* DataType */
67 code span.dv { color: #f67400; } /* DecVal */
68 code span.er { color: #da4453; text-decoration: underline; } /* Error */
69 code span.ex { color: #0099ff; font-weight: bold; } /* Extension */
70 code span.fl { color: #f67400; } /* Float */
71 code span.fu { color: #8e44ad; } /* Function */
72 code span.im { color: #27ae60; } /* Import */
73 code span.in { color: #c45b00; } /* Information */
74 code span.kw { color: #cfcfc2; font-weight: bold; } /* Keyword */
75 code span.op { color: #cfcfc2; } /* Operator */
76 code span.ot { color: #27ae60; } /* Other */
77 code span.pp { color: #27ae60; } /* Preprocessor */
78 code span.re { color: #2980b9; background-color: #153042; } /* RegionMarker */
79 code span.sc { color: #3daee9; } /* SpecialChar */
80 code span.ss { color: #da4453; } /* SpecialString */
81 code span.st { color: #f44f4f; } /* String */
82 code span.va { color: #27aeae; } /* Variable */
83 code span.vs { color: #da4453; } /* VerbatimString */
84 code span.wa { color: #da4453; } /* Warning */
85 </style>
86 <link rel="stylesheet" href="reveal.js/css/theme/superblack.css" id="theme">
87 <!-- Printing and PDF exports -->
88 <script>
89 var link = document.createElement( 'link' );
90 link.rel = 'stylesheet';
91 link.type = 'text/css';
92 link.href = window.location.search.match( /print-pdf/gi ) ? 'reveal.js/css/print/pdf.css' : 'reveal.js/css/print/paper.css';
93 document.getElementsByTagName( 'head' )[0].appendChild( link );
94 </script>
95 <!--[if lt IE 9]>
96 <script src="reveal.js/lib/js/html5shiv.js"></script>
97 <![endif]-->
98 <style>
99 div.sourceCode {
100 background-color: transparent;
101 overflow: auto;
102 margin: 0em;
103 }
104 </style>
105</head>
106<body>
107 <div class="reveal">
108 <div class="slides">
111<section id="функциональное-программирование" class="slide level1">
112<h1>Функциональное программирование</h1>
113<aside class="notes">
114<p>Функциональное программирование это не про использование map filter reduce. Функциональное программирование это вообще ортогонально к ооп. ИМХО проблема с ООП – наследование (которое тоже ортогонально к ООП) – нет разграничения между абстракцией и реализацией. и вообще обзывание это функциональным программированием – не совсем правильно. то, что мы сейчас будем пытаться сделать – сделать код более переиспользуемым. сделать наши данные максимально тупыми =&gt; переиспользуемыми. пытаться комбинировать слишком умные куски – не получится – слишком сложно. мы хотим сделать простые куски, которые просто комбинировать и еще чтобы компилятор проверял эти наши комбинации на валидность.</p>
115</aside>
116</section>
117<section class="slide level1">
119<p>Функциональное программирование:</p>
120<blockquote>
121<p>функции – это тоже данные.</p>
122</blockquote>
123<p><code>Int -&gt; Bool</code> (функция) – ровно такие же данные как и <code>Int</code>. Их также можно складывать в структуры, передавать как аргументы и т. п.</p>
124</section>
125<section id="нотация" class="slide level1">
126<h1>нотация</h1>
127</section>
128<section class="slide level1">
130<table width="100%">
131<tr>
132<td>
133<div class="sourceCode" id="cb1"><pre class="sourceCode java"><code class="sourceCode java"><span id="cb1-1"><a href="#cb1-1"></a> <span class="dt">int</span> x;</span></code></pre></div>
134</td>
135<td>
136<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1"></a><span class="ot"> x ::</span> <span class="dt">Int</span></span></code></pre></div>
137</td>
138</tr>
139<tr class="fragment">
140<td>
141<div class="sourceCode" id="cb3"><pre class="sourceCode java"><code class="sourceCode java"><span id="cb3-1"><a href="#cb3-1"></a> <span class="dt">int</span> <span class="fu">f</span>(<span class="dt">int</span> x)</span></code></pre></div>
142</td>
143<td>
144<div class="sourceCode" id="cb4"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb4-1"><a href="#cb4-1"></a><span class="ot"> f ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span></span></code></pre></div>
145</td>
146</tr>
147<tr class="fragment">
148<td>
149<div class="sourceCode" id="cb5"><pre class="sourceCode java"><code class="sourceCode java"><span id="cb5-1"><a href="#cb5-1"></a> <span class="dt">static</span> &lt;T&gt; T <span class="fu">f</span>(T x)</span></code></pre></div>
150</td>
151<td>
152<div class="sourceCode" id="cb6"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb6-1"><a href="#cb6-1"></a><span class="ot"> f ::</span> a <span class="ot">-&gt;</span> a</span></code></pre></div>
153</td>
154</tr>
155</table>
156</section>
157<section class="slide level1">
159<table width="100%">
160<tr>
161<td>
162<div class="sourceCode" id="cb7"><pre class="sourceCode java"><code class="sourceCode java"><span id="cb7-1"><a href="#cb7-1"></a> <span class="dt">static</span> &lt;T&gt; T <span class="fu">f</span>(T x)</span></code></pre></div>
163</td>
164<td>
165<div class="sourceCode" id="cb8"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb8-1"><a href="#cb8-1"></a><span class="ot"> f ::</span> a <span class="ot">-&gt;</span> a</span></code></pre></div>
166</td>
167</tr>
168<tr>
169<td class="fragment">
170<div class="sourceCode" id="cb9"><pre class="sourceCode java"><code class="sourceCode java"><span id="cb9-1"><a href="#cb9-1"></a> <span class="fu">f</span>(x);</span></code></pre></div>
171</td>
172<td class="fragment">
173<div class="sourceCode" id="cb10"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb10-1"><a href="#cb10-1"></a> f x</span></code></pre></div>
174</td>
175</tr>
176<tr class="fragment">
177<td>
178<div class="sourceCode" id="cb11"><pre class="sourceCode java"><code class="sourceCode java"><span id="cb11-1"><a href="#cb11-1"></a> <span class="fu">f</span>(x, y);</span></code></pre></div>
179</td>
180<td>
181<div class="sourceCode" id="cb12"><pre class="sourceCode fragment haskell"><code class="sourceCode haskell"><span id="cb12-1"><a href="#cb12-1"></a> f x y</span></code></pre></div>
182<div class="sourceCode" id="cb13"><pre class="sourceCode fragment haskell"><code class="sourceCode haskell"><span id="cb13-1"><a href="#cb13-1"></a> f x y <span class="ot">=</span> (f x) y</span></code></pre></div>
183</td>
184</td>
185</tr>
186</table>
187<aside class="notes">
188<p>Left-associative Currying</p>
189</aside>
190</section>
191<section class="slide level1">
193<table width="100%">
194<tr>
195<td>
196<div class="sourceCode" id="cb14"><pre class="sourceCode java"><code class="sourceCode java"><span id="cb14-1"><a href="#cb14-1"></a> <span class="dt">static</span> &lt;T&gt; T <span class="fu">f</span>(T x)</span>
197<span id="cb14-2"><a href="#cb14-2"></a> <span class="dt">static</span> &lt;T&gt; T <span class="fu">g</span>(T x)</span></code></pre></div>
198</td>
199<td>
200<div class="sourceCode" id="cb15"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb15-1"><a href="#cb15-1"></a><span class="ot"> f ::</span> a <span class="ot">-&gt;</span> a</span>
201<span id="cb15-2"><a href="#cb15-2"></a><span class="ot"> g ::</span> a <span class="ot">-&gt;</span> a</span></code></pre></div>
202</td>
203</tr>
204<tr>
205<td>
206<div class="sourceCode" id="cb16"><pre class="sourceCode java"><code class="sourceCode java"><span id="cb16-1"><a href="#cb16-1"></a> <span class="fu">f</span>(<span class="fu">g</span>(x));</span>
207<span id="cb16-2"><a href="#cb16-2"></a> <span class="fu">g</span>(<span class="fu">f</span>(x));</span></code></pre></div>
208</td>
209<td>
210<div class="sourceCode" id="cb17"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb17-1"><a href="#cb17-1"></a> f (g x)</span>
211<span id="cb17-2"><a href="#cb17-2"></a> g (f x)</span></code></pre></div>
212</td>
213</tr>
214</table>
215</section>
216<section id="композиция" class="slide level1">
217<h1>Композиция</h1>
218</section>
219<section class="slide level1">
221<div class="sourceCode" id="cb18"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb18-1"><a href="#cb18-1"></a><span class="ot">f ::</span> a <span class="ot">-&gt;</span> a</span>
222<span id="cb18-2"><a href="#cb18-2"></a><span class="ot">g ::</span> a <span class="ot">-&gt;</span> a</span></code></pre></div>
223<div class="sourceCode" id="cb19"><pre class="sourceCode fragment haskell"><code class="sourceCode haskell"><span id="cb19-1"><a href="#cb19-1"></a>f (g x)</span></code></pre></div>
224<div class="sourceCode" id="cb20"><pre class="sourceCode fragment haskell"><code class="sourceCode haskell"><span id="cb20-1"><a href="#cb20-1"></a>(f <span class="op">.</span> g) x <span class="op">==</span> f (g x)</span></code></pre></div>
225<div class="sourceCode" id="cb21"><pre class="sourceCode fragment haskell"><code class="sourceCode haskell"><span id="cb21-1"><a href="#cb21-1"></a>h <span class="ot">=</span> f <span class="op">.</span> g</span>
226<span id="cb21-2"><a href="#cb21-2"></a>h x <span class="op">==</span> f (g x)</span></code></pre></div>
227</section>
228<section class="slide level1">
230<div class="sourceCode" id="cb22"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb22-1"><a href="#cb22-1"></a><span class="ot">f ::</span> a <span class="ot">-&gt;</span> a</span>
231<span id="cb22-2"><a href="#cb22-2"></a><span class="ot">g ::</span> a <span class="ot">-&gt;</span> a</span></code></pre></div>
232<div class="sourceCode" id="cb23"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb23-1"><a href="#cb23-1"></a><span class="ot">h ::</span> a <span class="ot">-&gt;</span> a</span>
233<span id="cb23-2"><a href="#cb23-2"></a>h <span class="ot">=</span> f <span class="op">.</span> g</span></code></pre></div>
234<h3 class="fragment" id="моноид" class="fragment">моноид</h3>
235<aside class="notes">
236<p>моноид – у тебя есть две штуки одного типа и ты можешь получить еще одну штуку такого же типа. Это очень простой способ рождения сложности из простоты причем тип h выводится из определения. Нам его указывать не надо. если у нас изначальные маленькие кусочки хорошо описаны, то порожденные большие кусочки будут автоматически хорошо описанными.</p>
237</aside>
238</section>
239<section class="slide level1">
241<h2 id="моноид-1">Моноид</h2>
242<p><span class="fragment">Бинарная асоциативная операция</span></p>
243<div class="sourceCode" id="cb24"><pre class="sourceCode fragment haskell"><code class="sourceCode haskell"><span id="cb24-1"><a href="#cb24-1"></a><span class="ot">(.) ::</span> (a <span class="ot">-&gt;</span> a) <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> a) <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> a)</span></code></pre></div>
244<p><span class="fragment">Нейтральный элемент</span></p>
245<div class="sourceCode" id="cb25"><pre class="sourceCode fragment haskell"><code class="sourceCode haskell"><span id="cb25-1"><a href="#cb25-1"></a><span class="fu">id</span><span class="ot"> ::</span> a <span class="ot">-&gt;</span> a</span>
246<span id="cb25-2"><a href="#cb25-2"></a><span class="fu">id</span> x <span class="ot">=</span> x</span></code></pre></div>
247</section>
248<section id="haskell" class="slide level1">
249<h1>Haskell</h1>
250</section>
251<section class="slide level1">
253<h3 id="чисто-функционаьлный">Чисто функционаьлный</h3>
254<p>Все что функция может сделать – посмотреть на свои аргументы это вернуть значение.</p>
255<aside class="notes">
256<p>Нельзя просто произвольно распечатать строку в консоль, нельзя просто произвольно отправить запрос на бд, нельзя просто произвольно изменить глобальную переменную.</p>
257</aside>
258</section>
259<section class="slide level1">
261<h3 id="referential-transparency">Referential transparency</h3>
262<h5 id="любую-константу-можно-заменить-на-само-значение">(Любую константу можно заменить на само значение)</h5>
263<div class="sourceCode" id="cb26"><pre class="sourceCode java fragment"><code class="sourceCode java"><span id="cb26-1"><a href="#cb26-1"></a><span class="dt">int</span> x = <span class="dv">8</span>;</span>
264<span id="cb26-2"><a href="#cb26-2"></a><span class="dt">int</span> y = x++;</span>
265<span id="cb26-3"><a href="#cb26-3"></a><span class="bu">System</span>.<span class="fu">out</span>.<span class="fu">println</span>(y + <span class="st">&quot; might be the same as &quot;</span> + y);</span></code></pre></div>
266<div class="sourceCode" id="cb27"><pre class="sourceCode java fragment"><code class="sourceCode java"><span id="cb27-1"><a href="#cb27-1"></a><span class="dt">int</span> x = <span class="dv">8</span>;</span>
267<span id="cb27-2"><a href="#cb27-2"></a><span class="bu">System</span>.<span class="fu">out</span>.<span class="fu">println</span>(x++ + <span class="st">&quot; might be the same as &quot;</span> + x++);</span></code></pre></div>
268<aside class="notes">
269<p>Сильно упрощает рефакторинг и понимание кода.</p>
270</aside>
271</section>
272<section class="slide level1">
274<h3 id="нет-переменных-циклов-и-условных-переходов">Нет переменных, циклов и условных переходов</h3>
275<p><span class="fragment">Зато есть константы и нормальная рекурсия (А переходов вообще нет)</span></p>
276</section>
277<section class="slide level1">
279<h3 id="очень-ленивый">Очень ленивый</h3>
280<div class="sourceCode" id="cb28"><pre class="sourceCode haskell fragment"><code class="sourceCode haskell"><span id="cb28-1"><a href="#cb28-1"></a>xs <span class="ot">=</span> [<span class="dv">4</span>, <span class="dv">1</span>, <span class="dv">3</span>, <span class="dv">2</span>]</span>
281<span id="cb28-2"><a href="#cb28-2"></a>xs&#39; <span class="ot">=</span> <span class="fu">sort</span> xs</span>
282<span id="cb28-3"><a href="#cb28-3"></a><span class="fu">print</span> xs</span></code></pre></div>
283<div class="fragment">
284<p><code>xs'</code> не нужен чтобы распечатать <code>xs</code>, поэтому сортироваться ничто не будет. (Зачем делать то, что можно не делать)</p>
285</div>
286</section>
287<section class="slide level1">
289<p>Если хотите быстро и просто потыкаться, тут есть интерктивная штука:</p>
290<p><a href="https://www.haskell.org">haskell.org</a></p>
291</section>
292<section id="синтаксис" class="slide level1">
293<h1>Синтаксис</h1>
294</section>
295<section id="функции" class="slide level1">
296<h1>Функции</h1>
297</section>
298<section class="slide level1">
300<div class="sourceCode" id="cb29"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb29-1"><a href="#cb29-1"></a><span class="ot">add2 ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span></span>
301<span id="cb29-2"><a href="#cb29-2"></a>add2 x <span class="ot">=</span> x <span class="op">+</span> <span class="dv">2</span></span></code></pre></div>
302<p>Все функции и константы всегда обозначаются словами с маленькой буквы без пробелов.</p>
303<p>(Константы это просто функции с нулем аргументов.)</p>
304</section>
305<section class="slide level1">
307<h2 id="pattern-mathcing">Pattern mathcing</h2>
308<div class="sourceCode" id="cb30"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb30-1"><a href="#cb30-1"></a><span class="ot">fixBuz ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">String</span></span>
309<span id="cb30-2"><a href="#cb30-2"></a>divide8 <span class="dv">3</span> <span class="ot">=</span> <span class="st">&quot;Fiz&quot;</span></span>
310<span id="cb30-3"><a href="#cb30-3"></a>divide8 <span class="dv">5</span> <span class="ot">=</span> <span class="st">&quot;Buz&quot;</span></span>
311<span id="cb30-4"><a href="#cb30-4"></a>divide8 <span class="dv">15</span> <span class="ot">=</span> <span class="st">&quot;FizBuz&quot;</span></span>
312<span id="cb30-5"><a href="#cb30-5"></a>divide8 _ <span class="ot">=</span> <span class="st">&quot;Some other number&quot;</span></span></code></pre></div>
313<p>Так матчить можно произвольные структуры произвольного уровня вложенности.</p>
314<p><code>_</code> – специальное название константы, которое говорит что вам все равно что в ней лежит.</p>
315<aside class="notes">
316<p>функции объявляются в несколькро строк. Первая – обьявленик типа функции, а последубщие – реализация. В общем случае тип можно не указывать, но указывать тип у высказыванй на самом верхнем уровне (не вложенные) считается хорошим тоном и улучшает выведение типов и ошибки компиляции. У функции может быть несколько реализаций: какая из них вызовется зависит от значений передаваемых аргументов. матчинг произхводится сверху вниз. если в аргемантах написано слово с маленькой буквы, то значение аргумента биндится на эту константу.</p>
317</aside>
318</section>
319<section class="slide level1">
321<h2 id="структуры">Структуры</h2>
322</section>
323<section class="slide level1">
325<div class="sourceCode" id="cb31"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb31-1"><a href="#cb31-1"></a><span class="kw">data</span> <span class="dt">Foo</span> <span class="ot">=</span> <span class="dt">Bar</span></span>
326<span id="cb31-2"><a href="#cb31-2"></a><span class="ot">foo ::</span> <span class="dt">Bar</span></span>
327<span id="cb31-3"><a href="#cb31-3"></a>foo <span class="ot">=</span> <span class="dt">Bar</span></span></code></pre></div>
328<p><code>Foo</code> – тип структуры. <code>Bar</code> – конструктор структуры.</p>
329<p>Тут у <code>Foo</code> всего одно значение <code>Bar</code>.</p>
330</section>
331<section class="slide level1">
333<h2 id="произведение-типов">Произведение типов</h2>
334<h5 id="обычные-поля-структур">(обычные поля структур)</h5>
335<aside class="notes">
336<p>После констрктора можно укзать существующие типы, которые в нем храняться.</p>
337</aside>
338<div class="sourceCode" id="cb32"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb32-1"><a href="#cb32-1"></a><span class="kw">data</span> <span class="dt">PersonType</span> <span class="ot">=</span> <span class="dt">Person</span> <span class="dt">String</span> <span class="dt">Int</span></span></code></pre></div>
339<div class="sourceCode" id="cb33"><pre class="sourceCode haskell fragment"><code class="sourceCode haskell"><span id="cb33-1"><a href="#cb33-1"></a><span class="ot">vasya ::</span> <span class="dt">PersonType</span></span>
340<span id="cb33-2"><a href="#cb33-2"></a>vasya <span class="ot">=</span> <span class="dt">Person</span> <span class="st">&quot;Vasya&quot;</span> <span class="dv">8</span></span>
341<span id="cb33-3"><a href="#cb33-3"></a><span class="co">-- тип можно не укзывать</span></span>
342<span id="cb33-4"><a href="#cb33-4"></a>petya <span class="ot">=</span> <span class="dt">Person</span> <span class="st">&quot;Petya&quot;</span> <span class="dv">5</span></span></code></pre></div>
343<div class="sourceCode" id="cb34"><pre class="sourceCode haskell fragment"><code class="sourceCode haskell"><span id="cb34-1"><a href="#cb34-1"></a><span class="ot">getName ::</span> <span class="dt">PersonType</span> <span class="ot">-&gt;</span> <span class="dt">String</span></span>
344<span id="cb34-2"><a href="#cb34-2"></a>getName (<span class="dt">Person</span> name _) <span class="ot">=</span> name</span></code></pre></div>
345<div class="sourceCode" id="cb35"><pre class="sourceCode haskell fragment"><code class="sourceCode haskell"><span id="cb35-1"><a href="#cb35-1"></a><span class="ot">greetPerson ::</span> <span class="dt">PersonType</span> <span class="ot">-&gt;</span> <span class="dt">String</span></span>
346<span id="cb35-2"><a href="#cb35-2"></a>greetPerson p <span class="ot">=</span> <span class="st">&quot;Hello, &quot;</span> <span class="op">++</span> getName p</span></code></pre></div>
347<div class="sourceCode" id="cb36"><pre class="sourceCode haskell fragment"><code class="sourceCode haskell"><span id="cb36-1"><a href="#cb36-1"></a>greetPerson petya</span>
348<span id="cb36-2"><a href="#cb36-2"></a><span class="co">-- &quot;Hello, Petya&quot;</span></span></code></pre></div>
349<h3 id="еще-немного-функций">Еще немного функций</h3>
350<pre><code>greetPerson :: PersonType -&gt; String
351greetPerson p = &quot;Hello, &quot; ++ getName p
353greetPerson :: PersonType -&gt; String
354greetPerson p = &quot;Hello, &quot; ++ name
355 where
356 name = getName p
358greetPerson :: PersonType -&gt; String
359greetPerson p = &quot;Hello, &quot; ++ name
360 where
361 getName&#39; (Person name _) = name
362 name = getName&#39; p
364data PersonType = Person String Int
366getName :: PersonType -&gt; String
367getName (Person name _) = name
369greetName :: String -&gt; String
370greetName name = &quot;Hello, &quot; ++ name
372greetPerson :: PersonType -&gt; String
373greetPerson p = greetName (getName p)
375greetPerson :: PersonType -&gt; String
376greetPerson = greetName . getName
378greetPerson petya
379-- &quot;Hello, Petya&quot;
381(greetName . getName) petya
382-- &quot;Hello, Petya&quot;</code></pre>
383<h3 id="суммы-типов">Суммы типов</h3>
384<p>Функции нескольких аргументов – странный синтаксис – потом расскажу.</p>
385<pre><code>data Bool = False | True
387x :: Bool
388x = True
389y = False
391ifThenElse :: (Bool, a, a) -&gt; a
393ifThenElse (True, a, _) = a
394ifThenElse (False, _, b) = b
396ifThenElse (True, &quot;Hello&quot;, &quot;World&quot;)
397-- &quot;Hello&quot;
399ifThenElse (False, &quot;Hello&quot;, &quot;World&quot;)
400-- &quot;World&quot;
402data CircleType = Circle Double Double Double
403data RectangleType = Rectangle Double Double Double Double
405data Shape =
406 CircleShape CircleType | RectangleShape RectangleType
408surface :: Shape -&gt; Double
410surface (CircleShape (Circle _ _ r)) =
411 pi * r ^ 2
413surface (RectangleShape (Rectangle x1 y1 x2 y2)) =
414 (abs (x2 - x1)) * (abs (y2 - y1))
416shape = CircleShape (Circle 0 0 2)
417surface shape
418-- 12.566370614359172
420otherShape = RectangleShape (Rectangle 1 2 3 4)
421surface otherShape
422-- 4.0</code></pre>
423<h2 id="и-еще-немного-функций">И еще немного функций</h2>
424<h3 id="лямбда-выражения">Лямбда-выражения</h3>
425<pre><code>add8 :: Int -&gt; Int
427add8 x = x + 8
429add8 = \x -&gt; x + 8</code></pre>
430<p>λ – <code>\\</code> (λ печатать тяжело)</p>
431<pre><code>foo :: (Int -&gt; Int) -&gt; Int
433foo add8
435foo (\x -&gt; x + 8)</code></pre>
436<h3 id="давайте-придумаем-синтаксис-для-функции-нескольких-аргументов">Давайте придумаем синтаксис для функции нескольких аргументов!</h3>
437<pre><code>x, y :: Int
438x = 42
439y = 69
441xPlusY :: Int
442xPlusY = add x y</code></pre>
443<p>Применение функции – лево-ассоциативно</p>
444<pre><code>xPlusY = (add x) y
446xPlusY = f y
447f = add x
449f :: Int -&gt; Int
451add :: Int -&gt; (Int -&gt; Int)
453add :: Int -&gt; (Int -&gt; Int)</code></pre>
454<p>Тип <code>-\&gt;</code> – право-ассоциативный</p>
455<pre><code>add :: Int -&gt; Int -&gt; Int
457add a b = a + b
459add = \a b -&gt; a + b</code></pre>
460<p>Любая функция берет строго один аргумент.</p>
461<p>Функция нескольких аргументов все равно берет строго одтн аргумент и возвращает функцию, которая берет следйющий.</p>
462<p><em>(И из-за того, что применение функции лево-ассоциативно, вызов таких не трубует особого синтаксиса.)</em></p>
463<h3 id="currying">Currying</h3>
464<pre><code>add :: Int -&gt; Int -&gt; Int
465add a b = a + b
467add8 :: Int -&gt; Int
469add :: Int -&gt; (Int -&gt; Int)
471add8 = add 8
473add8 3
474-- 11</code></pre>
475<h3 id="funny-fact">Funny fact</h3>
476<p>Оператор (например <code>+</code>) – функция, название которой не содержит буквы и цифры.</p>
477<pre><code>x +&amp;+ y = x + y
4798 +&amp;+ 9
480-- 17</code></pre>
481<h3 id="funny-fact-2">Funny fact 2</h3>
482<p>Оператор можно превратить в функцию, окружив его скобками.</p>
483<pre><code>add :: Int -&gt; Int -&gt; Int
484add x y = x + y
486add = (+&amp;+)
488add = (+)</code></pre>
489<h3 id="funny-fact-3">Funny fact 3</h3>
490<p>Функцию можно превратить в оператор, окружив ее обратными кавычками.</p>
491<pre><code>add :: Int -&gt; Int -&gt; Int
492add x y = x + y
494add 8 9
495-- 17
4978 `add` 9
498-- 17</code></pre>
499<h2 id="список">Список</h2>
500<h3 id="односвязный-список">Односвязный список</h3>
501<pre><code>data IntList = Cons Int IntList | Nil
503nums :: IntList
504nums = 1 `Cons` (2 `Cons` (3 `Cons` Nil))
506sum :: IntList -&gt; Int
508sum (Cons x xs) = x + sum xs
510sum Nil = 0
511sum (Cons x xs) = x + sum xs
513sum nums
514-- 6
516take :: Int -&gt; IntList -&gt; IntList
518take _ Nil = Nil
519take 0 _ = Nil
520take n (Cons x xs) = Cons x (take (n - 1) xs)
522nums :: IntList
523nums = 1 `Cons` (2 `Cons` (3 `Cons` Nil))
525take 2 nums
526-- Cons 1 (Cons 2 Nil)
527take 1029 nums
528-- Cons 1 (Cons 2 (Cons 3 Nil))
529take 0 nums
530-- Nil
532repeat :: Int -&gt; IntList
534repeat n = n : (repeat n)
536repeat 8
537-- Cons 8 (Cons 8 (Cons 8 (Cons 8 (Cons 8 (Cons 8 (Cons 8 (Cons 8 (Cons 8 (Cons 8 (...
539(take 3 . repeat) 8
540-- Cons 8 (Cons 8 (Cons 8 Nil))
542(sum . take 3 . repeat) 8
543-- 24</code></pre>
544<table>
545<colgroup>
546<col style="width: 50%" />
547<col style="width: 50%" />
548</colgroup>
549<tbody>
550<tr class="odd">
551<td>Наша самодеятельность</td>
552<td>В стандартной библиотеке</td>
553</tr>
554<tr class="even">
555<td><pre><code>IntList</code></pre></td>
556<td><pre><code>[Int]</code></pre></td>
557</tr>
558<tr class="odd">
559<td><pre><code>Nil</code></pre></td>
560<td><pre><code>[]</code></pre></td>
561</tr>
562<tr class="even">
563<td><pre><code>Cons</code></pre></td>
564<td><pre><code>:</code></pre></td>
565</tr>
566<tr class="odd">
567<td><pre><code>Cons 3 (Cons 4 Nil)</code></pre></td>
568<td><pre class="fragment"><code>3 : 4 : []</code></pre>
569<pre class="fragment"><code>[3, 4]</code></pre></td>
570</tr>
571</tbody>
572</table>
573<p><code>repeat</code>, <code>sum</code> и <code>take</code> тоже есть в стандартной библиотеке.</p>
574<h2 id="quicksort">QuickSort</h2>
575<pre><code>quicksort :: [Int] -&gt; [Int]
577quicksort (x:xs) =
578 quicksort smaller ++ [x] ++ quicksort larger
579 where
580 smaller = filter (&lt; x) xs
581 larger = filter (&gt;= x) xs
583filter :: (Bool -&gt; Int) -&gt; [Int] -&gt; [Int]
585filter f (x:xs) =
586 if f x
587 then filter f xs
588 else x:(filter f xs)
590filter _ [] = []
591filter f (x:xs) =
592 if f x
593 then filter f xs
594 else x:(filter f xs)
596quicksort :: [Int] -&gt; [Int]
597quicksort (x:xs) =
598 quicksort smaller ++ [x] ++ quicksort larger
599 where
600 smaller = filter (&lt; x) xs
601 larger = filter (&gt;= x) xs
602 filter _ [] = []
603 filter f (x:xs) =
604 if f x
605 then filter f xs
606 else x:(filter f xs)
608quicksort :: [Int] -&gt; [Int]
609quicksort [] = []
610quicksort (x:xs) =
611 quicksort smaller ++ [x] ++ quicksort larger
612 where
613 smaller = filter (&lt; x) xs
614 larger = filter (&gt;= x) xs
615 filter _ [] = []
616 filter f (x:xs) =
617 if f x
618 then filter f xs
619 else x:(filter f xs)
621quicksort [2, 1, 3, 4]
622-- [1, 2, 3, 4]</code></pre>
623<p><code>filter</code> тоже есть в стандартной библиотеке.</p>
624<h2 id="где-и-как-смотреть-стандартную-библиотеку">Где и как смотреть "стандартную библиотеку"</h2>
625<ol type="1">
626<li class="fragment"><p><a href="https://hackage.haskell.org/package/base">Hackage</a></p>
627<p>(Там вам нужен только пакет <code>base</code>. Ссылка ведет прямо на него.) Еще если там нажать <code>s</code>, то будет поиск.</p></li>
628<li class="fragment"><p><a href="https://hoogle.haskell.org">Hoogle</a></p>
629<p>Это поиск по типам. Например: <code>Int -\&gt; \[Int\] -\&gt; \[Int\]</code> (Тут вам опять же нужен только пакет <code>base</code>. Нужно чтобы справа было "package:base".) –&gt;</p></li>
630</ol>
631</section>
632 </div>
633 </div>
635 <script src="reveal.js/js/reveal.js"></script>
637 <script>
639 // Full list of configuration options available at:
640 // https://github.com/hakimel/reveal.js#configuration
641 Reveal.initialize({
642 // Push each slide change to the browser history
643 history: true,
645 // Optional reveal.js plugins
646 dependencies: [
647 { src: 'reveal.js/lib/js/classList.js', condition: function() { return !document.body.classList; } },
648 { src: 'reveal.js/plugin/zoom-js/zoom.js', async: true },
649 { src: 'reveal.js/plugin/notes/notes.js', async: true }
650 ]
651 });
652 </script>
653 </body>
654</html>