<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.8.5">Jekyll</generator><link href="https://slamii.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://slamii.github.io/" rel="alternate" type="text/html" /><updated>2019-06-14T10:50:53+00:00</updated><id>https://slamii.github.io/feed.xml</id><title type="html">slamii</title><subtitle>Sławek Blicharz &amp; Sami Kozłowski</subtitle><entry><title type="html">Window functions</title><link href="https://slamii.github.io/Window-functions/" rel="alternate" type="text/html" title="Window functions" /><published>2019-06-13T00:00:00+00:00</published><updated>2019-06-13T00:00:00+00:00</updated><id>https://slamii.github.io/Window-functions</id><content type="html" xml:base="https://slamii.github.io/Window-functions/">&lt;p class=&quot;excerpt&quot;&gt;Window functions in SQL, their syntax, benefits and coverage in MySQL and PostgreSQL.&lt;/p&gt;

&lt;h3 id=&quot;outline-with-an-example&quot;&gt;Outline with an example&lt;/h3&gt;

&lt;p&gt;Window functions are functions applied to sets of rows. They can be used in &lt;code class=&quot;highlighter-rouge&quot;&gt;SELECT&lt;/code&gt; or &lt;code class=&quot;highlighter-rouge&quot;&gt;ORDER BY&lt;/code&gt; clauses. Think of an SQL &lt;code class=&quot;highlighter-rouge&quot;&gt;SELECT&lt;/code&gt; query that selects $S$ rows and that for each row $r$ makes some calculation involving other rows, for example assigns rank to customer orders according to their value.&lt;/p&gt;

&lt;p&gt;What a window function does is for each processed row $r$ in $S$ it defines a set of rows called a &lt;em&gt;window&lt;/em&gt;, let’s denote it $W_r$, and this window provides the context for the window function to operate within. For example, if $r$ is a row describing an order, $W_r$ could be a set of all the orders from which to determine the rank of $r$. &lt;em&gt;Windowing&lt;/em&gt; means applying calculations to a set of rows and returning a single value. Let’s be quick to jump to an example:&lt;/p&gt;

&lt;div class=&quot;gist-wrapper&quot;&gt;&lt;script src=&quot;https://gist.github.com/slamii/74853d572c88c37e709d420d2409017d.js&quot;&gt;&lt;/script&gt;&lt;/div&gt;

&lt;p&gt;The query above could yield results like the following:&lt;/p&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;id&lt;/span&gt;      &lt;span class=&quot;n&quot;&gt;order_date&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;     &lt;span class=&quot;n&quot;&gt;rank&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;------- ----------- --------- ----&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;       &lt;span class=&quot;mi&quot;&gt;2019&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;03&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;23&lt;/span&gt;  &lt;span class=&quot;mi&quot;&gt;56&lt;/span&gt;        &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;       &lt;span class=&quot;mi&quot;&gt;2019&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;02&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;  &lt;span class=&quot;mi&quot;&gt;40&lt;/span&gt;        &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;       &lt;span class=&quot;mi&quot;&gt;2019&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;03&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;23&lt;/span&gt;  &lt;span class=&quot;mi&quot;&gt;33&lt;/span&gt;        &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In this example the selected rows $S$ are all the rows from &lt;code class=&quot;highlighter-rouge&quot;&gt;Sample.Table&lt;/code&gt;. For each row $r$, the &lt;code class=&quot;highlighter-rouge&quot;&gt;OVER&lt;/code&gt; clause creates its own, independent window $W_r$. Here each window is the same and consists, again, of all the rows in the table, so $W_r = S$. This is because &lt;code class=&quot;highlighter-rouge&quot;&gt;OVER&lt;/code&gt; does impose any restrictions on the windows, only ordering. Subsequently, both $r$ and $W_r$ are passed to the window function &lt;code class=&quot;highlighter-rouge&quot;&gt;RANK()&lt;/code&gt;. It computes the rank of a given record $r$ as one more than the number of rows in $W_r$ that have a greater ordering value than $r$.&lt;/p&gt;

&lt;h3 id=&quot;syntax&quot;&gt;Syntax&lt;/h3&gt;

&lt;p&gt;The general form of a window function clause is &lt;code class=&quot;highlighter-rouge&quot;&gt;function(&amp;lt;args&amp;gt;) OVER([&amp;lt;partition clause&amp;gt;][&amp;lt;order clause&amp;gt;][&amp;lt;frame clause&amp;gt;]])&lt;/code&gt;. Subsequent sections cover each part in more detail.&lt;/p&gt;

&lt;h4 id=&quot;partitioning&quot;&gt;Partitioning&lt;/h4&gt;

&lt;p&gt;Specified by the &lt;code class=&quot;highlighter-rouge&quot;&gt;PARTITION BY&lt;/code&gt; clause, partitioning restricts the scope of $W_r$ to only those rows from $S$ that have the same values in the partitioning columns as the current row $r$.&lt;/p&gt;

&lt;p&gt;For example, the following query would print each sales value next to its associated customer id together with its percentage share among all sales values for this customer. Here &lt;code class=&quot;highlighter-rouge&quot;&gt;SUM()&lt;/code&gt; is the window function and &lt;code class=&quot;highlighter-rouge&quot;&gt;PARTITION BY&lt;/code&gt; restricts $W_r$ to only those rows that have the same value in &lt;code class=&quot;highlighter-rouge&quot;&gt;customer_id&lt;/code&gt; as $r$ does.&lt;/p&gt;

&lt;div class=&quot;gist-wrapper&quot;&gt;&lt;script src=&quot;https://gist.github.com/slamii/ec1836acb2658054617f094b27fa5406.js&quot;&gt;&lt;/script&gt;&lt;/div&gt;

&lt;h4 id=&quot;ordering&quot;&gt;Ordering&lt;/h4&gt;

&lt;p&gt;Ordering is defined by the &lt;code class=&quot;highlighter-rouge&quot;&gt;ORDER BY&lt;/code&gt; clause which defines the order for the calculation within $W_r$. With ranking functions like &lt;code class=&quot;highlighter-rouge&quot;&gt;RANK()&lt;/code&gt; or &lt;code class=&quot;highlighter-rouge&quot;&gt;ROW_NUMBER()&lt;/code&gt; this is pretty straightforward. Compare the example in the outline section; we obviously have to specify by which column we want to rank the records and this is the role of the &lt;code class=&quot;highlighter-rouge&quot;&gt;ORDER BY value DESC&lt;/code&gt; part.&lt;/p&gt;

&lt;p&gt;However, for aggregate window functions like &lt;code class=&quot;highlighter-rouge&quot;&gt;SUM()&lt;/code&gt; or &lt;code class=&quot;highlighter-rouge&quot;&gt;AVG()&lt;/code&gt; ordering of the rows does not matter. In this case, it is only used to give meaning to the framing options which are covered in the next section.&lt;/p&gt;

&lt;h4 id=&quot;framing&quot;&gt;Framing&lt;/h4&gt;

&lt;p&gt;Framing, like partitioning, is a filter that restricts the rows in $W_r$. It is applicable to aggregate window functions and to three of the offset functions: &lt;code class=&quot;highlighter-rouge&quot;&gt;FIRST_VALUE()&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;LAST_VALUE()&lt;/code&gt;, and &lt;code class=&quot;highlighter-rouge&quot;&gt;NTH_VALUE()&lt;/code&gt; and requires an ordering imposed on the window. Based on this ordering $W_r$ is framed to contain only a selection of rows.&lt;/p&gt;

&lt;p&gt;The window frame clause can include three parts and takes the following form &lt;code class=&quot;highlighter-rouge&quot;&gt;&amp;lt;window frame units&amp;gt; &amp;lt;window frame extent&amp;gt; [&amp;lt;window frame exclusion&amp;gt;]&lt;/code&gt;. We shall briefly describe each part before presenting a couple of short examples.&lt;/p&gt;

&lt;p&gt;Frame units specify the way in which the frame is determined. It can be either &lt;code class=&quot;highlighter-rouge&quot;&gt;ROWS&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;RANGE&lt;/code&gt; or &lt;code class=&quot;highlighter-rouge&quot;&gt;GROUPS&lt;/code&gt;, the last one not supported by MySQL and only supported by PostgreSQL of version at least 11.&lt;/p&gt;

&lt;p&gt;The frame extent part describes the boundaries quantitatively - once we know &lt;strong&gt;how&lt;/strong&gt; we specify the frame, what units we use, we have to describe &lt;strong&gt;how big&lt;/strong&gt; it is going to be. For this we use the statements &lt;code class=&quot;highlighter-rouge&quot;&gt;UNBOUNDED PRECEDING/FOLLOWING&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;&amp;lt;n&amp;gt; PRECEDING/FOLLOWING&lt;/code&gt; or &lt;code class=&quot;highlighter-rouge&quot;&gt;CURRENT ROW&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The window frame-exclusion option specifies what to do with the current row and its peers in case of ties. Has the form &lt;code class=&quot;highlighter-rouge&quot;&gt;EXCLUDE CURRENT ROW/GROUP/TIES/NO OTHERS&lt;/code&gt; (default), not supported by MySQL, the last three supported by Postgres from version 11.&lt;/p&gt;

&lt;h4 id=&quot;framing-examples&quot;&gt;Framing examples&lt;/h4&gt;

&lt;p&gt;Suppose our dataset is contained within the table &lt;code class=&quot;highlighter-rouge&quot;&gt;Example.Data&lt;/code&gt; and contains the following records:&lt;/p&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;id&lt;/span&gt;         &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;-------    -------&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;          &lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;          &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;          &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;          &lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;          &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h5 id=&quot;framing-with-rows&quot;&gt;Framing with ROWS&lt;/h5&gt;

&lt;p&gt;The &lt;code class=&quot;highlighter-rouge&quot;&gt;ROWS&lt;/code&gt; option allows to indicate the bounds of the frame as an offset from $r$ in the number of rows. Let’s take the example of the following query:&lt;/p&gt;

&lt;div class=&quot;gist-wrapper&quot;&gt;&lt;script src=&quot;https://gist.github.com/slamii/ebd30730927ac29012215b7a55a33612.js&quot;&gt;&lt;/script&gt;&lt;/div&gt;

&lt;p&gt;It would yield the following result:&lt;/p&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; &lt;span class=&quot;n&quot;&gt;id&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;sum&lt;/span&gt; 
&lt;span class=&quot;c1&quot;&gt;-------    --------&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;          &lt;span class=&quot;mi&quot;&gt;35&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;          &lt;span class=&quot;mi&quot;&gt;40&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;          &lt;span class=&quot;mi&quot;&gt;55&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;          &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;          &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;For each $r$ the query defines $W_r$ to be $r$ together with all preceding and one following row (in the order given by &lt;code class=&quot;highlighter-rouge&quot;&gt;id&lt;/code&gt;). Thus for &lt;code class=&quot;highlighter-rouge&quot;&gt;id = 3&lt;/code&gt; the &lt;code class=&quot;highlighter-rouge&quot;&gt;sum&lt;/code&gt; is equal to &lt;code class=&quot;highlighter-rouge&quot;&gt;55&lt;/code&gt; as a sum of &lt;code class=&quot;highlighter-rouge&quot;&gt;value&lt;/code&gt; for &lt;code class=&quot;highlighter-rouge&quot;&gt;id = 1, 2, 3, 4&lt;/code&gt;. One could use &lt;code class=&quot;highlighter-rouge&quot;&gt;EXCLUDE CURRENT ROW&lt;/code&gt; in the query to exclude &lt;code class=&quot;highlighter-rouge&quot;&gt;id = 3&lt;/code&gt; here.&lt;/p&gt;

&lt;h5 id=&quot;framing-with-range&quot;&gt;Framing with RANGE&lt;/h5&gt;

&lt;p&gt;The &lt;code class=&quot;highlighter-rouge&quot;&gt;RANGE&lt;/code&gt; option defines the bounds in terms of a difference with respect to $r$’s value. Take a look at the following:&lt;/p&gt;

&lt;div class=&quot;gist-wrapper&quot;&gt;&lt;script src=&quot;https://gist.github.com/slamii/cdf66b4435be4ab4181b29dbff661d26.js&quot;&gt;&lt;/script&gt;&lt;/div&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;id&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;sum&lt;/span&gt; 
&lt;span class=&quot;c1&quot;&gt;-------   --------&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;         &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;         &lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;         &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;         &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;         &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Notice the change in ordering in both &lt;code class=&quot;highlighter-rouge&quot;&gt;ORDER BY&lt;/code&gt;’s. Now we defined the sum to be over all the rows that have &lt;code class=&quot;highlighter-rouge&quot;&gt;value&lt;/code&gt; at least 4 smaller than $r$ and at most equal to the value of $r$. Hence for example &lt;code class=&quot;highlighter-rouge&quot;&gt;id = 5&lt;/code&gt; has &lt;code class=&quot;highlighter-rouge&quot;&gt;sum = 14&lt;/code&gt; as the only rows within this range are &lt;code class=&quot;highlighter-rouge&quot;&gt;id = 5, 3&lt;/code&gt;.&lt;/p&gt;

&lt;h5 id=&quot;framing-with-groups&quot;&gt;Framing with GROUPS&lt;/h5&gt;

&lt;p&gt;Finally, the &lt;code class=&quot;highlighter-rouge&quot;&gt;GROUPS&lt;/code&gt; option frames the window to a number of groups of rows, a ‘group’ meaning the rows with the same value.&lt;/p&gt;

&lt;div class=&quot;gist-wrapper&quot;&gt;&lt;script src=&quot;https://gist.github.com/slamii/bc1b5459528de2d660f5a6e74659dd35.js&quot;&gt;&lt;/script&gt;
&lt;/div&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;id&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;sum&lt;/span&gt; 
&lt;span class=&quot;c1&quot;&gt;-------   --------&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;         &lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;         &lt;span class=&quot;mi&quot;&gt;39&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;         &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;         &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;
&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;         &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Consequently, &lt;code class=&quot;highlighter-rouge&quot;&gt;sum&lt;/code&gt; for &lt;code class=&quot;highlighter-rouge&quot;&gt;id = 1&lt;/code&gt; is &lt;code class=&quot;highlighter-rouge&quot;&gt;50&lt;/code&gt; as a sum of &lt;code class=&quot;highlighter-rouge&quot;&gt;id = 1, 4&lt;/code&gt; (the &lt;code class=&quot;highlighter-rouge&quot;&gt;value = 15&lt;/code&gt; group) and &lt;code class=&quot;highlighter-rouge&quot;&gt;id = 2&lt;/code&gt; (the next group, &lt;code class=&quot;highlighter-rouge&quot;&gt;value = 20&lt;/code&gt;). Had we used &lt;code class=&quot;highlighter-rouge&quot;&gt;EXCLUDE GROUP&lt;/code&gt; here, &lt;code class=&quot;highlighter-rouge&quot;&gt;id = 1, 4&lt;/code&gt; would be neglected in this case, while &lt;code class=&quot;highlighter-rouge&quot;&gt;EXCLUDE TIES&lt;/code&gt; would count only one of them.&lt;/p&gt;

&lt;h3 id=&quot;comparison-to-other-approaches&quot;&gt;Comparison to other approaches&lt;/h3&gt;

&lt;p&gt;An alternative to using window functions could be grouped queries. However, these give us insight into aggregates, but we lose the details. For example, let’s say we have a database of books, and each book has its weight and an owner. For each book, we want to calculate the percentage of the current weight of the bookworm’s total, and maybe a difference from the average. If you aggregate the data by owner, you don’t have access to individual weights.&lt;/p&gt;

&lt;p&gt;A common way to handle this is to have a query that groups the data, define a table expression based on this query, and then join it with the main table to match the detail with the aggregate. Here’s a query that uses this approach:&lt;/p&gt;

&lt;div class=&quot;gist-wrapper&quot;&gt;&lt;script src=&quot;https://gist.github.com/slamii/cdbe35ee2ac7e54c8eb14a1ae4dd4277.js&quot;&gt;&lt;/script&gt;&lt;/div&gt;

&lt;p&gt;But what if you also need to include percentages and differences from the global aggregates (including all the owners)? You would have to create another table expression and another join. It quickly gets complicated.&lt;/p&gt;

&lt;p&gt;Another approach is to use subqueries:&lt;/p&gt;

&lt;div class=&quot;gist-wrapper&quot;&gt;&lt;script src=&quot;https://gist.github.com/slamii/a5c3e2000906f6bc5483a1b7477b0053.js&quot;&gt;&lt;/script&gt;&lt;/div&gt;

&lt;p&gt;It suffers from the same problem: complication. What’s more, most (if not all) SQL optimizers are not clever enough to use the fact that the subquery uses the same rows, and therefore perform multiple accesses.&lt;/p&gt;

&lt;p&gt;Look how simple it becomes with window functions:&lt;/p&gt;

&lt;div class=&quot;gist-wrapper&quot;&gt;&lt;script src=&quot;https://gist.github.com/slamii/7def37a0c6e3685217e5cddc8c442725.js&quot;&gt;&lt;/script&gt;&lt;/div&gt;

&lt;h3 id=&quot;bibliography&quot;&gt;Bibliography&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;Microsoft SQL Server 2012 High-Performance T-SQL Using Window Functions, Itzik Ben-Gan&lt;/li&gt;
  &lt;li&gt;&lt;a name=&quot;wf-bib2&quot; href=&quot;https://blog.jooq.org/2018/07/05/postgresql-11s-support-for-sql-standard-groups-and-exclude-window-function-clauses/&quot;&gt;PostgreSQL 11’s Support for SQL Standard GROUPS and EXCLUDE Window Function Clauses, blog.jooq.org&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a name=&quot;wf-bib3&quot; href=&quot;https://dev.mysql.com/doc/refman/8.0/en/window-functions-frames.html&quot;&gt;Window Function Frame Specification, dev.mysql.com&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;</content><author><name></name></author><summary type="html">Window functions in SQL, their syntax, benefits and coverage in MySQL and PostgreSQL.</summary></entry><entry><title type="html">Docker symlink security hole</title><link href="https://slamii.github.io/Docker-vulnerability/" rel="alternate" type="text/html" title="Docker symlink security hole" /><published>2019-06-04T00:00:00+00:00</published><updated>2019-06-04T00:00:00+00:00</updated><id>https://slamii.github.io/Docker-vulnerability</id><content type="html" xml:base="https://slamii.github.io/Docker-vulnerability/">&lt;p class=&quot;excerpt&quot;&gt;On 28th May a senior software engineer Aleksa Sarai discovered a security hole within Docker which can grant an attacker read and write access to any file on the host machine regardless of its permissions.&lt;/p&gt;

&lt;h3 id=&quot;toctou-vulnerability&quot;&gt;TOCTOU vulnerability&lt;/h3&gt;
&lt;p&gt;TOCTOU stands for time-of-check to time-of-use and is a race condition vulnerability resulting in inconsistent state of a system, usually a file system. When two or more processes operate on one resource, some of them may perform modifications based on an incorrect past state of that resource.&lt;/p&gt;

&lt;p&gt;Consider a database of email recipients. One possible email would be sent to users who haven’t logged in to the app for at least 30 days. Let’s assume a job performs this task once a day, first selecting a set of users who satisfy the criterion (last login more than 30 days before), then resolving an email template, maybe calling an external service for some additional data, and then sending the emails to the selected users. While the server was resolving the template, Bob, who hasn’t been using the app for a while, logs in. He would still receive the email.&lt;/p&gt;

&lt;p&gt;In general, despite their apparent simplicity, TOCTOU problems are usually very hard to solve when both consistency and performance are needed.&lt;/p&gt;

&lt;h3 id=&quot;bug-location&quot;&gt;Bug location&lt;/h3&gt;
&lt;p&gt;The Docker vulnerability affects the &lt;code class=&quot;highlighter-rouge&quot;&gt;FollowSymlinkInScope&lt;/code&gt; function used by many docker tools, notably &lt;code class=&quot;highlighter-rouge&quot;&gt;docker cp&lt;/code&gt; that copies files between containers and the host machine. The purpose of &lt;code class=&quot;highlighter-rouge&quot;&gt;FollowSymlinkInScope&lt;/code&gt; is to take a given symlink pointing to some path and safely resolve it as though the process was inside a container.&lt;/p&gt;

&lt;p&gt;Take for example &lt;code class=&quot;highlighter-rouge&quot;&gt;docker cp /path1 container1:/path2/sym1&lt;/code&gt; executed on the host. It would copy a file from &lt;code class=&quot;highlighter-rouge&quot;&gt;/path1&lt;/code&gt; to the location within &lt;code class=&quot;highlighter-rouge&quot;&gt;container1&lt;/code&gt; to which &lt;code class=&quot;highlighter-rouge&quot;&gt;sym1&lt;/code&gt; points, say &lt;code class=&quot;highlighter-rouge&quot;&gt;/loc1&lt;/code&gt;. &lt;code class=&quot;highlighter-rouge&quot;&gt;/loc1&lt;/code&gt; only makes sense within the container; it does not refer to &lt;code class=&quot;highlighter-rouge&quot;&gt;/loc1&lt;/code&gt; on the host machine. Hence &lt;code class=&quot;highlighter-rouge&quot;&gt;sym1&lt;/code&gt; has to be resolved to something else; to &lt;code class=&quot;highlighter-rouge&quot;&gt;/loc1&lt;/code&gt; at some hidden location $\ell$ on the host that Docker process uses internally as &lt;code class=&quot;highlighter-rouge&quot;&gt;container1&lt;/code&gt;’s insides.&lt;/p&gt;

&lt;p&gt;The problem with &lt;code class=&quot;highlighter-rouge&quot;&gt;FollowSymlinkInScope&lt;/code&gt; is that after the symlink is resolved, it is passed around a little more before it is actually used - in the case of &lt;code class=&quot;highlighter-rouge&quot;&gt;docker cp&lt;/code&gt; to do the copying. The usage phase assumes the path is safe to use since the resolution has been done in a safely manner before.&lt;/p&gt;

&lt;p&gt;But it can happen that an attacker adds a symlink component to the path after the resolution but before the actual use, hitting the TOCTOU window. Then the symlink will not be treated specially and can therefore point to a file on the host machine.&lt;/p&gt;

&lt;p&gt;Continuing the above example, &lt;code class=&quot;highlighter-rouge&quot;&gt;container1:/path2/sym1&lt;/code&gt; has been resolved to &lt;code class=&quot;highlighter-rouge&quot;&gt;/loc1&lt;/code&gt; within $\ell$. But suppose at attacker managed to swap &lt;code class=&quot;highlighter-rouge&quot;&gt;/sym1&lt;/code&gt; for another symlink, now pointing to &lt;code class=&quot;highlighter-rouge&quot;&gt;/loc2&lt;/code&gt;, before &lt;code class=&quot;highlighter-rouge&quot;&gt;docker cp&lt;/code&gt; started the actual copying. Since we are after the resolving phase, &lt;code class=&quot;highlighter-rouge&quot;&gt;docker cp&lt;/code&gt; will not realise that it should search for &lt;code class=&quot;highlighter-rouge&quot;&gt;/loc2&lt;/code&gt; within $\ell$. It will take it as given, referring to a file on the host machine.&lt;/p&gt;

&lt;p&gt;If used maliciously, this can give the attacker read and write permissions to any file on the host machine, even without appropriate permissions.&lt;/p&gt;

&lt;h3 id=&quot;exploitation-with-docker-cp&quot;&gt;Exploitation with docker cp&lt;/h3&gt;
&lt;p&gt;Aleksa provided exemplary tools to showcase the security hole on the example of &lt;code class=&quot;highlighter-rouge&quot;&gt;docker cp&lt;/code&gt; command. Let’s see what he did.&lt;/p&gt;

&lt;h4 id=&quot;attack-setup&quot;&gt;Attack setup&lt;/h4&gt;
&lt;p&gt;Assume we are a regular user on the host machine with docker permissions but without root access. We want to retrieve a root-only file from the system, say &lt;code class=&quot;highlighter-rouge&quot;&gt;/w00t_w00t_im_a_flag&lt;/code&gt;. So the first thing that Aleksa does is he creates this file, prints some ‘secret’ message there and &lt;code class=&quot;highlighter-rouge&quot;&gt;chmod&lt;/code&gt;’s it to &lt;code class=&quot;highlighter-rouge&quot;&gt;000&lt;/code&gt; so that only root should have access to it.&lt;/p&gt;

&lt;p&gt;Then he builds an runs a malicious container and subsequently starts an attack.&lt;/p&gt;

&lt;h4 id=&quot;container-contents&quot;&gt;Container contents&lt;/h4&gt;
&lt;p&gt;The container used for the attack also contains &lt;code class=&quot;highlighter-rouge&quot;&gt;/w00t_w00t_im_a_flag&lt;/code&gt; file with a different, ‘ordinary’ message. The container executes a single C program which creates a symlink &lt;code class=&quot;highlighter-rouge&quot;&gt;/totally_safe_path&lt;/code&gt; pointing to &lt;code class=&quot;highlighter-rouge&quot;&gt;/&lt;/code&gt;. It also creates an empty directory. The program then atomically swaps the two in a loop until the end of time.&lt;/p&gt;

&lt;h4 id=&quot;the-attack&quot;&gt;The attack&lt;/h4&gt;
&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;docker cp container1:/totally_safe_path/w00t_w00t_im_a_flag&lt;/code&gt; is invoked in a never-ending loop, copying each time to a different directory. The underlying container keeps swapping around the symlink at &lt;code class=&quot;highlighter-rouge&quot;&gt;/totally_safe_path&lt;/code&gt;. If it manages to insert the symlink to &lt;code class=&quot;highlighter-rouge&quot;&gt;/&lt;/code&gt; after the resolution by &lt;code class=&quot;highlighter-rouge&quot;&gt;FollowSymlinkInScope&lt;/code&gt;, then &lt;code class=&quot;highlighter-rouge&quot;&gt;/&lt;/code&gt; will resolve to the root of the host machine and the file that should be inaccessible will be copied and compromised. If the symlink stays there throughout the operation of &lt;code class=&quot;highlighter-rouge&quot;&gt;docker cp&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;/&lt;/code&gt; will resolve to the container’s root and we will simply copy the ‘ordinary’ message.&lt;/p&gt;

&lt;p&gt;Aleksa commented that there is a &amp;lt;1% chance of hitting the TOCTOU window with this script. This means that it only takes roughly a 10s attack to get hold of the ‘secret’ file.&lt;/p&gt;

&lt;h3 id=&quot;fallout&quot;&gt;Fallout&lt;/h3&gt;
&lt;p&gt;Aleksa and Docker security team agreed that the public disclosure of the issue is legitimate even without a fix available.&lt;/p&gt;

&lt;p&gt;The most comprehensive solution to the problem would require changes to the core pieces of Docker which is not possible. Some partial solutions are underway and as for now Docker officials said that possible attack scenario is “rare/unlikely” so the flaw, while serious, is not necessarily an emergency.&lt;/p&gt;

&lt;h3 id=&quot;bibliography&quot;&gt;Bibliography&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;a name=&quot;docker_bib1&quot; href=&quot;https://seclists.org/oss-sec/2019/q2/131&quot;&gt;CVE-2018-15664, Security Mailing List Archive&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a name=&quot;docker_bib2&quot; href=&quot;https://duo.com/decipher/docker-bug-allows-root-access-to-host-file-system&quot;&gt;Docker Bug Allows Root Access to Host Filesystem, Decipher&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a name=&quot;docker_bib3&quot; href=&quot;https://github.com/moby/moby/blob/master/pkg/symlink/fs.go#L19&quot;&gt;Github, FollowSymlinkInScope, 04.06.2019&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a name=&quot;docker_bib4&quot; href=&quot;https://securityaffairs.co/wordpress/86272/hacking/docker-race-condition-flaw.html&quot;&gt;All Docker versions affected by an unpatched race condition issue, Security Affairs&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;</content><author><name></name></author><summary type="html">On 28th May a senior software engineer Aleksa Sarai discovered a security hole within Docker which can grant an attacker read and write access to any file on the host machine regardless of its permissions.</summary></entry><entry><title type="html">Monads for the inquisitive</title><link href="https://slamii.github.io/Monads/" rel="alternate" type="text/html" title="Monads for the inquisitive" /><published>2019-03-18T00:00:00+00:00</published><updated>2019-03-18T00:00:00+00:00</updated><id>https://slamii.github.io/Monads</id><content type="html" xml:base="https://slamii.github.io/Monads/">&lt;p class=&quot;excerpt&quot;&gt;Why we need monads, what they are and where we can see them.&lt;/p&gt;

&lt;h3 id=&quot;motivational-introduction&quot;&gt;Motivational introduction&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Outlines what purpose monads serve in computer science.&lt;br /&gt; The shaded paragraphs are supposed to be more in-depth and give a mathematical background; they can be omitted and it should not affect the overall understanding.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Functional languages are founded on the idea of function composition; having $f: A \longrightarrow B$ and $g: B \longrightarrow C$ we can create a composition $gf: A \longrightarrow C$. 
Suppose now those functions have some additional, common behaviour. Maybe they sometimes don’t return a result (e.g. because something is undefined) or maybe they return a varying number of results.&lt;/p&gt;

&lt;p&gt;In a strongly typed language we’d represent this additional behaviour by
a different type of the return value. Let’s stick to the example of
possibly not returning a value. We’d introduce a type constructor &lt;code class=&quot;highlighter-rouge&quot;&gt;Maybe&lt;/code&gt;, $M$ for short, and our functions would have signatures $f:A \longrightarrow MB$ and $g:B \longrightarrow MC$.&lt;/p&gt;

&lt;p&gt;We still do want to compose them. The additional behaviour shouldn’t be a problem; both functions have it. But now the types are incompatible. We want to apply $g$ after $f$ but $g$ accepts type $B$, not $MB$. We are stuck. Monads are a device to break this impasse; let’s keep this in mind for the rest of the section.&lt;/p&gt;

&lt;p class=&quot;advanced&quot;&gt;Taking a step back, another thing besides composition of functions that we can employ is the identity function $id: A \longrightarrow A$, a trivial computation for any type $A$. Now, it turns out that there is a mathematical structure built on top of these two properties - a category.&lt;/p&gt;

&lt;p class=&quot;advanced&quot;&gt;It belongs to category theory, a mathematical area that tries to describe things in the most general way possible. Thus the definition of a category is very non-specific. Intuitively, it's a thing with some objects and with some things between these objects (like functions between sets). Formally:&lt;/p&gt;
&lt;div class=&quot;advanced&quot;&gt;&lt;blockquote&gt;
	&lt;p&gt;A &lt;strong&gt;category&lt;/strong&gt; $\mathcal{C}$ is a collection of:&lt;/p&gt;
	&lt;ol&gt;
		&lt;li&gt;&lt;strong&gt;objects&lt;/strong&gt; $A, B, \ldots$&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;arrows&lt;/strong&gt; $f:A\longrightarrow B, \ldots$&lt;/li&gt;
	&lt;/ol&gt;
	&lt;p&gt;where the arrows have the objects of $\mathcal{C}$ as domain and codomain. The arrows of corresponding domains and codomains have to be composable in the way you'd expect and each object has its &lt;strong&gt;identity arrow&lt;/strong&gt; $id_A:A \longrightarrow A$ such that composing an identity with any function gives back the function, e.g. $fid_A = f = id_Bf$.&lt;/p&gt;
&lt;/blockquote&gt;&lt;/div&gt;

&lt;p class=&quot;advanced&quot;&gt;For more details refer to chapter 1 in [&lt;a href=&quot;#monad_bib2&quot;&gt;1&lt;/a&gt;]. So the types of a programming language together with its functions form a category.&lt;/p&gt;

&lt;p class=&quot;advanced&quot;&gt;Further into category theory, there is a notion of a &lt;strong&gt;monad&lt;/strong&gt;. It is different from the computer science monad we are discussing and we are not going to give its definition (the reader can refer to 5.1 in [&lt;a href=&quot;#monad_bib2&quot;&gt;1&lt;/a&gt;]). But it is closely related to the one we are interested in.&lt;/p&gt;

&lt;p class=&quot;advanced&quot;&gt;A monad $M$ on a category $\mathcal{C}$ gives us another category, the &lt;strong&gt;Kleisli category&lt;/strong&gt; $\mathcal{C}_\mathbb{M}$. The only thing we need to know about it is that its arrows are the arrows in $\mathcal{C}$ of the form $f:A\longrightarrow MB$. Because the Kleisli category is ineed a category, we can compose those arrows - which is precisely what we wanted.&lt;/p&gt;

&lt;p&gt;The upshot is as follows: if we have functions with some additional behaviour represented by $f:A\longrightarrow MB$ and if the type constructor $M$ has some nice properties, then we can compose those functions despite an apparent type inconsistency. This is what monads are all about.&lt;/p&gt;

&lt;h3 id=&quot;what-is-a-monad&quot;&gt;What is a monad?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Presents two definitions of a monad in computer science.&lt;br /&gt; 
The shaded paragraphs serve as their comparison and discussion. They are more mathematically involved and can be safely skipped if they bring more harm than good.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Much in the spirit of the above reasoning, the definition of a computer science monad can be given as follows ([&lt;a href=&quot;#monad_bib5&quot;&gt;5&lt;/a&gt;]):&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;A &lt;strong&gt;monad&lt;/strong&gt; is a map $M$:&lt;/p&gt;
  &lt;ol&gt;
    &lt;li&gt;sending every type $X$ of a given programming language to a new type
$MX$.&lt;/li&gt;
    &lt;li&gt;equipped with a rule for composing two functions of the form
$f: X \longrightarrow MY$ and
$g: Y \longrightarrow MZ$ to $gf: X\longrightarrow MZ$.
The functions are called &lt;strong&gt;Kleisli functions&lt;/strong&gt; and the composition the &lt;strong&gt;Kleisli composition&lt;/strong&gt;.&lt;/li&gt;
    &lt;li&gt;together with a map $\mathrm{pure}_X: X\longrightarrow MX$
for every type $X$ that acts trivially in the composition.
The Kleisli composition is required to be &lt;a href=&quot;https://en.wikipedia.org/wiki/Associative_property&quot;&gt;associative&lt;/a&gt;.&lt;/li&gt;
  &lt;/ol&gt;
&lt;/blockquote&gt;

&lt;p&gt;The Kleisli functions are the functions with additional behaviour discussed in the previous section.&lt;/p&gt;

&lt;p&gt;A more practical definition offered by Haskell [&lt;a href=&quot;#monad_bib1&quot;&gt;1&lt;/a&gt;] states:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;A &lt;strong&gt;monad&lt;/strong&gt; is:&lt;/p&gt;
  &lt;ol&gt;
    &lt;li&gt;a type constructor $m$&lt;/li&gt;
    &lt;li&gt;a function $a \longrightarrow ma$ building values of type $m$, called &lt;strong&gt;return&lt;/strong&gt;&lt;/li&gt;
    &lt;li&gt;a combinator function called &lt;strong&gt;bind&lt;/strong&gt; of the form $(ma, a \longrightarrow mb)\longrightarrow mb$ for any types $a, b$. Typically denoted $x\ {\scriptstyle \gg=}\ f$.&lt;/li&gt;
  &lt;/ol&gt;
&lt;/blockquote&gt;

&lt;p&gt;So given a monadic value $x$ of type $ma$ and Kleisli function $f: a\longrightarrow mb$ the bind function gives us a way to apply $f$ to $x$. The monad above has to also satisfy the laws equivalent to the third point in the previous definition.&lt;/p&gt;

&lt;p class=&quot;advanced&quot;&gt;A natural question to ask would be about the meaning of the $\mathrm{pure}$ function (and its counterpart from the second definition - bind). If all we want is a composition of Kleisli functions and this is guaranteed by the second point in the definition, why bother with the third?&lt;/p&gt;

&lt;p class=&quot;advanced&quot;&gt;$\mathrm{pure}$ and bind are in some sense trivial computations; ones such that composing them with others does not make any difference. They provide an &quot;obvious&quot; or &quot;natural&quot; way to get from a value in $X$ to a value in $MX$.&lt;/p&gt;

&lt;p class=&quot;advanced&quot;&gt;The fact that such trivial computations exist ensures that $M$ is not too weird, that it has some nice structure. Mathematically speaking, this means that the computations of the form $A\longrightarrow MB$ form a category (the Kleisli category we mentioned before).&lt;/p&gt;

&lt;p class=&quot;advanced&quot;&gt;The requirement of being a category is a really basic one. If we don't insist on it and don't require the existence of $\mathrm{pure}$ function, we would allow some very irregular and strange structures to be monands. Ones that would be irregular enough to not have any practical value anyway. It's better to simply disregard them.&lt;/p&gt;

&lt;p class=&quot;advanced&quot;&gt;For now we will leave it as an open question: what are those irregular structures? What &quot;monads&quot; would we get if we didn't require the $\mathrm{pure}$ and bind functions and their associated laws in the definition?&lt;/p&gt;

&lt;p class=&quot;advanced&quot; style=&quot;margin-top: 2em;&quot;&gt;Another question we might want to ask concerns the relation between the two definitions. Are they equivalent? First points are clearly the same. $\mathrm{pure}$ for a given type is the same as bind and the associated laws are already stated to be equivalent. The only question is whether having Kleisli composition is the same as having the bind combinator.&lt;/p&gt;

&lt;p class=&quot;advanced&quot;&gt;Indeed if we have a bind function then we get a Kleisli composition by defining $gf(x) := f(x)\ {\scriptstyle \gg=}\ g$. Before looking into whether a Kleisli composition gives us bind let's look at the Haskell definition more closely; the findings below are not immediately obvious but the reader will be spared the detailed proofs.&lt;/p&gt;

&lt;p class=&quot;advanced&quot;&gt;The three points of the second definition together with its laws ensure that the return function is injective for any type $a$ unless $ma$ is trivial. In both cases $m$ is a functor and $(m, \mathrm{return}, \left(\mathrm{return}_m)^{-1}\right)$ is a monad in the category theory sense.&lt;/p&gt;

&lt;p class=&quot;advanced&quot;&gt;If $\mathrm{pure}_X$ from the first definition happens to be injective as well then indeed we get a bind from the second. In general however, it looks as though it need not be.&lt;/p&gt;

&lt;p class=&quot;advanced&quot;&gt;Again, we leave these as open questions: can we construct a monad as in the first definition without $\mathrm{pure}_X$ being injective? Can $M$ be non-monadic in category theory sense? Can it be non-functorial?&lt;/p&gt;

&lt;p&gt;So in general the first definition seems broader than the second. However, in all practical and useful cases in which computer science is actually interested the two definitions coincide and one should forget the potential discrepancy.&lt;/p&gt;

&lt;h3 id=&quot;examples-of-monads-in-programming-languages&quot;&gt;Examples of monads in programming languages&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Three examples: language-agnostic list constructor, Optionals from Java as semimonad and random number generators from Haskell.&lt;/em&gt;&lt;/p&gt;

&lt;h4 id=&quot;a-list-constructor&quot;&gt;A list constructor&lt;/h4&gt;

&lt;p&gt;A list constructor $L$ can be given a structure of a monad. Kleisli functions in this case are functions returning a varying number of results.&lt;/p&gt;

&lt;p&gt;Let’s take an example of a function $f$ that takes a chess position and returns a list of possible chess positions after one move. We want compose two such functions $f: \mathrm{ChPos}\longrightarrow L\mathrm{ChPos}$ to get a function computing possible chess possitions after two moves.&lt;/p&gt;

&lt;p&gt;How would we do that? $f(x)$ is a list of chess positions $[x_1, x_2, \ldots]$; we’d apply another $f$ to every such position getting a list of lists of positions $[[x_1’, \ldots], [x_2’, \ldots], \ldots]$. Then we’d flatten this list to a simple list of positions $[x_1’, \ldots, x_2’, \ldots]$.&lt;/p&gt;

&lt;p&gt;The $\mathrm{ChPos}$ is just an example, but it’s clear that we could do the same with all functions returning a list of elements. The bind is the operator applying a function to every element of a list and flattening the result. The return for an element $x$ returns a list containing this single element $[x]$. These two together with $L$ form a monad&lt;/p&gt;

&lt;h4 id=&quot;optionals-in-java&quot;&gt;Optionals in Java&lt;/h4&gt;

&lt;p&gt;Optionals are Java-implementation of the $\mathrm{Maybe}$ we took for an example in the first section. For instance, &lt;code class=&quot;highlighter-rouge&quot;&gt;Optional&amp;lt;String&amp;gt;&lt;/code&gt; can be thought of as a box which can either contain a &lt;code class=&quot;highlighter-rouge&quot;&gt;String&lt;/code&gt; or be empty.&lt;/p&gt;

&lt;p&gt;The Kleisli functions, are those that may not return a value. For example suppose the objects we work with are &lt;code class=&quot;highlighter-rouge&quot;&gt;Sheep&lt;/code&gt;. Those sheep have families and we can write functions returning a given sheep’s parent. But if the sheep is cloned, it does not have parents, the function would return &lt;code class=&quot;highlighter-rouge&quot;&gt;null&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If we ever want to write functions returning grandparents, we’d have to check first whether the father is defined and only in this case one could search for its parents. For great-grandparents it’s even worse; the deeper we go, the more ugly it becomes.&lt;/p&gt;

&lt;p&gt;But this seems wrong, doesn’t it? If we have a function returning the father, returning the grandfather &lt;strong&gt;should&lt;/strong&gt; be just a composition of two such functions. That’s the most clear and elegant solution, no &lt;code class=&quot;highlighter-rouge&quot;&gt;null&lt;/code&gt;-checking should be involved. Indeed, in this case Java has us do the following:&lt;/p&gt;

&lt;div class=&quot;gist-wrapper&quot;&gt;&lt;script src=&quot;https://gist.github.com/slamii/ff00d3ae93d62749c0f3478f7571f334.js&quot;&gt;&lt;/script&gt;&lt;/div&gt;

&lt;p&gt;where &lt;code class=&quot;highlighter-rouge&quot;&gt;Optional.ofNullable&lt;/code&gt; is the $\mathrm{return}$ function and &lt;code class=&quot;highlighter-rouge&quot;&gt;Optional.flatMap&lt;/code&gt; is the $\mathrm{bind}$. Looks like a monad and Kleisli composition!&lt;/p&gt;

&lt;p&gt;However, we mentioned before that a monad has to also satisfy some laws in order to really be a monad. It turns out that Java’s &lt;code class=&quot;highlighter-rouge&quot;&gt;Optional&lt;/code&gt; does not always abide these.&lt;/p&gt;

&lt;p&gt;One of those laws is the left identity which says that $\mathrm{bind}$-ing a function to a $\mathrm{return}$-ed value has to be the same as just applying the function to the value. In Java terms this reads:&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Optional.ofNullable(x).flatMap(f).equals(f.apply(x))&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;for any value &lt;code class=&quot;highlighter-rouge&quot;&gt;x&lt;/code&gt; and any Function &lt;code class=&quot;highlighter-rouge&quot;&gt;f&lt;/code&gt;. In other words, $\mathrm{return}$ is like an identity function. Whenever &lt;code class=&quot;highlighter-rouge&quot;&gt;x&lt;/code&gt; is not &lt;code class=&quot;highlighter-rouge&quot;&gt;null&lt;/code&gt; this works fine, but consider the following example:&lt;/p&gt;

&lt;div class=&quot;gist-wrapper&quot;&gt;&lt;script src=&quot;https://gist.github.com/slamii/e91e9ba23bf026ffc782327d4bb65cef.js&quot;&gt;&lt;/script&gt;&lt;/div&gt;

&lt;p&gt;This code breaks down; left side is an empty &lt;code class=&quot;highlighter-rouge&quot;&gt;Optional&lt;/code&gt;, and the right one - minus one.&lt;/p&gt;

&lt;p&gt;The problem here is that &lt;code class=&quot;highlighter-rouge&quot;&gt;Optional.ofNullable(null)&lt;/code&gt; is translated to &lt;code class=&quot;highlighter-rouge&quot;&gt;Optional.empty&lt;/code&gt;. So even if &lt;code class=&quot;highlighter-rouge&quot;&gt;f&lt;/code&gt; is defined to work on nullable values of &lt;code class=&quot;highlighter-rouge&quot;&gt;x&lt;/code&gt;, on the left-hand-side it never gets executed.&lt;/p&gt;

&lt;p&gt;Thus Java’s &lt;code class=&quot;highlighter-rouge&quot;&gt;Optional&lt;/code&gt; is not a full monad. What are the implications of this? For the answer as well as for some additional account of the topic consult [&lt;a href=&quot;#monad_bib4&quot;&gt;4&lt;/a&gt;].&lt;/p&gt;

&lt;h4 id=&quot;random-numbers-in-haskell&quot;&gt;Random numbers in Haskell&lt;/h4&gt;

&lt;p&gt;Consider generating random numbers in a purely functional language like Haskell. Purely functional means that any function always returns the same result for the same input. In this setting functions like &lt;code class=&quot;highlighter-rouge&quot;&gt;random()&lt;/code&gt; returning a random number from $(0, 1)$ are not allowed to exist; the input is always the same (empty) so the output has to be as well. The best we could do would be to imitate &lt;a href=&quot;https://xkcd.com/&quot;&gt;xkcd&lt;/a&gt;:&lt;/p&gt;

&lt;center&gt;&lt;img src=&quot;https://imgs.xkcd.com/comics/random_number.png&quot; /&gt;&lt;/center&gt;

&lt;p&gt;Jokes aside, how functions like &lt;code class=&quot;highlighter-rouge&quot;&gt;random()&lt;/code&gt; work in “traditional”, non-functional languages? They sample some data like mouse movements or time in nanoseconds from the system and produce a value based on these. Such implicit arguments are not allowed in functional languages, so what one has to do here is to pass this data explicitly as a parameter, in the form of some object.&lt;/p&gt;

&lt;p&gt;So, in languages like Haskell functions returning random values take a random number generator object, &lt;code class=&quot;highlighter-rouge&quot;&gt;rng&lt;/code&gt;, and return a value together with another &lt;code class=&quot;highlighter-rouge&quot;&gt;rng&lt;/code&gt; (in case we want to generate more numbers in the future. We can’t reuse the &lt;code class=&quot;highlighter-rouge&quot;&gt;rng&lt;/code&gt; that we passed initially – as explained above it would return the same value!). The signature of such functions is&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;r\longrightarrow(v, r)&lt;/script&gt;

&lt;p&gt;A function of this form is called a &lt;strong&gt;stateful computation&lt;/strong&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;sc&lt;/code&gt;, because what we are doing is passing some state $r$ to the function based on which it returns a value together with a new state. In the case of our example the state is the &lt;code class=&quot;highlighter-rouge&quot;&gt;rng&lt;/code&gt;. The type of an &lt;code class=&quot;highlighter-rouge&quot;&gt;sc&lt;/code&gt; is defined to be the type of the return value - $\mathrm{type}(v)$ in the above notation.&lt;/p&gt;

&lt;p&gt;Using these, to write a function returning three random numbers we’d need to write code like the following:&lt;/p&gt;

&lt;div class=&quot;gist-wrapper&quot;&gt;&lt;script src=&quot;https://gist.github.com/slamii/d309ffd77f9321b155bafd0be914db8a.js&quot;&gt;&lt;/script&gt;&lt;/div&gt;

&lt;p&gt;where we have to manually pass the subsequent &lt;code class=&quot;highlighter-rouge&quot;&gt;rngs&lt;/code&gt; to subsequent function calls. If the reader thinks this is ludicrous we totally agree and if she expects we are going to use monads to get around it, she is not mistaken.&lt;/p&gt;

&lt;p&gt;So, for a given type $a$, what could monadic $ma$ be? We really have only one choice - it’s going to be stateful computations with values in $a$. Thus the values of Kleisli functions are stateful computations. Their signature is:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;f: a \longrightarrow (r\longrightarrow(b,r))&lt;/script&gt;

&lt;p&gt;This means that $ma$ is a functional type - it’s values are functions, the &lt;code class=&quot;highlighter-rouge&quot;&gt;scs&lt;/code&gt;. Don’t get lost on this.&lt;/p&gt;

&lt;p&gt;We need to find bind and return functions for a complete monad. Starting with the latter, what would be a trivial &lt;code class=&quot;highlighter-rouge&quot;&gt;sc&lt;/code&gt; for a value $x$? It’s a function - one that yields $x$ for all states $r$.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\mathrm{return}\ x = r \longmapsto (x,r)&lt;/script&gt;

&lt;p&gt;To come up with a bind suppose we have an &lt;code class=&quot;highlighter-rouge&quot;&gt;sc&lt;/code&gt; $c: r \longrightarrow (a, r)$ of some type and a function $f: a \longrightarrow (r \longrightarrow (b, r))$ from that type to &lt;code class=&quot;highlighter-rouge&quot;&gt;scs&lt;/code&gt; of possibly some other type. E.g. $f(a)$ could be an &lt;code class=&quot;highlighter-rouge&quot;&gt;sc&lt;/code&gt; returning two values, the first of which is always $a$.&lt;/p&gt;

&lt;p&gt;$c\ {\scriptstyle &amp;gt;==}\  f$ is an &lt;code class=&quot;highlighter-rouge&quot;&gt;sc&lt;/code&gt;, name it $c’$. Intuitively, what we want it to do on a state $r$ is to do whatever $c$ did and then do whatever &lt;code class=&quot;highlighter-rouge&quot;&gt;sc&lt;/code&gt; returned by $f$ does. To be precise the definition of $c’$ is:&lt;/p&gt;

&lt;div class=&quot;gist-wrapper&quot;&gt;&lt;script src=&quot;https://gist.github.com/slamii/0fb7266cfeedf37335951c141271dfb0.js&quot;&gt;&lt;/script&gt;&lt;/div&gt;

&lt;p&gt;Now the function generating three random numbers with a bit of Haskell’s syntactic sugar can look as follows:&lt;/p&gt;

&lt;div class=&quot;gist-wrapper&quot;&gt;&lt;script src=&quot;https://gist.github.com/slamii/e1c70af633732420f9f1f1311a5a45f2.js&quot;&gt;&lt;/script&gt;&lt;/div&gt;

&lt;p&gt;Thus, what monads did to us is carrying out the pesky state passing implicitly, out of our sight, making the code look much more like what we would expect in a “traditional” language. For a more careful account of the topic you could refer to [&lt;a href=&quot;monad_bib3&quot;&gt;3&lt;/a&gt;].&lt;/p&gt;

&lt;h3 id=&quot;leibnizs-monads&quot;&gt;Leibniz’s monads&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;A taste of the meaning of monad in philosophy. Unrelated to computer science.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The term &lt;strong&gt;monad&lt;/strong&gt;, from Greek &lt;em&gt;monas&lt;/em&gt;, “unit”, was first used by Giordano Bruno.
He claimed the world is &lt;em&gt;homogeneous&lt;/em&gt;, &lt;em&gt;one&lt;/em&gt;; nevertheless, it consists of a multitude of self-contained units. Like a point, &lt;em&gt;mathematical minimum&lt;/em&gt;, is a basic component of space, and an atom, &lt;em&gt;physical minimum&lt;/em&gt;, of that of matter - monad is a &lt;em&gt;metaphysical minimum&lt;/em&gt;. Their shapes and forms are unique (which followed naturally from God being the ultimate perfect creator of infinite inventiveness).&lt;/p&gt;

&lt;p&gt;It was then picked up by Gottfried Wilhelm Leibniz, one of the most interesting philosophers of the 17th century. While he’s mostly known for the fundamental contributions to differential and integral calculus, his metaphysical system was equally groundbreaking in its cohesiveness and generality.&lt;/p&gt;

&lt;p&gt;Three hundred years ago the most enlightened minds of Europe were debating the problem of &lt;em&gt;substance&lt;/em&gt;. It may seem like a silly problem now (or, to be polite, a poorly defined one) but surprisingly, these old ideas influence our language and way of thinking even today.&lt;/p&gt;

&lt;p&gt;Rene Descartes rejected the then dominant school of thought, platonism, arguing that the &lt;em&gt;corporeal&lt;/em&gt; substance consists of only matter itself, that there are no &lt;a href=&quot;https://philosophynow.org/issues/90/Plato_A_Theory_of_Forms&quot;&gt;platonic forms&lt;/a&gt;. However, he went only so far in reducing the metaphysical overhead of previous generations - inspired by then state-of-the-art automatons on the streets of Paris, he introduced the distinction between body and mind. And that dualism lives on, three centuries later.&lt;/p&gt;

&lt;p&gt;Descartes struggled with explaining how exactly these two substances influence each other. His successors suggested various solutions, most of which seem odd nowadays:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;They don’t influence each other and they don’t have to because God does that for them&lt;/li&gt;
  &lt;li&gt;They may seem like two substances but in reality they are just two sides of the same coin, so to speak, namely God&lt;/li&gt;
  &lt;li&gt;There is no dualism, and only matter exists (no God here)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;But perhaps the most original solution was Leibniz’s. He claimed there is an infinite number of substances but they are of the same kind. In this respect his views were similar to materialists; but looking closer we discover significant differences.&lt;/p&gt;

&lt;p&gt;Leibniz believed that every phenomenon is unique, that everything differs from everything else, that there are no two identical leaves or drops of water. There are no two objects that differ only by their positions in space. However, things are &lt;em&gt;similar&lt;/em&gt;. Phenomena are continuous series (notice connection to differentials). Straight line is just a special case of a curve, equation - of inequality. Consciousness is a spectrum, a lie is the smallest truth, evil the smallest good. This was Leibniz’s &lt;em&gt;continuity law&lt;/em&gt; (lex continui). It allowed him to connect seemingly disjoint phenomena using a coherent framework. An interesting application of this theory was in psychology, where he introduced unconscious states of mind long before Freud (claiming that these were only &lt;em&gt;weak&lt;/em&gt; forms of consciousness).&lt;/p&gt;

&lt;p&gt;This law, along with his &lt;em&gt;metaphysical pluralism&lt;/em&gt; was perhaps the most revolutionary thesis of Leibniz’s philosophy. And here, finally, we come to monads - this is how he called these simple individual &lt;em&gt;units of being&lt;/em&gt;.
Unfortunately for computer science-oriented readers, they have little in common with Haskell. Perhaps the most significant is that they &lt;em&gt;don’t have windows&lt;/em&gt;, as Leibniz said, each of them being a closed universe that acts upon its environment but cannot be influenced from outside.&lt;/p&gt;

&lt;h3 id=&quot;bibliography&quot;&gt;Bibliography&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;a name=&quot;monad_bib1&quot; href=&quot;https://wiki.haskell.org/All_About_Monads&quot;&gt;All About Monads, Wiki Haskell&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a name=&quot;monad_bib2&quot; href=&quot;http://pi.math.cornell.edu/~dmehrle/notes/partiii/cattheory_partiii_notes.pdf&quot;&gt;Category Theory, 2015, Peter Johnstone&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a name=&quot;monad_bib3&quot; href=&quot;http://learnyouahaskell.com/for-a-few-monads-more&quot;&gt;For a Few Monads More, Learn You a Haskell for Great Good!&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a name=&quot;monad_bib4&quot; href=&quot;https://www.sitepoint.com/how-optional-breaks-the-monad-laws-and-why-it-matters/&quot;&gt;How Optional Breaks the Monad Laws and Why It Matters, Sitepoint&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a name=&quot;monad_bib5&quot; href=&quot;https://ncatlab.org/nlab/show/monad+%28in+computer+science%29&quot;&gt;Monad (in computer science), nLab&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a name=&quot;monad_bib6&quot; href=&quot;https://www.schoolofhaskell.com/school/starting-with-haskell/basics-of-haskell/13-the-list-monad&quot;&gt;The List Monad, School of Haskell&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a name=&quot;monad_bib7&quot; href=&quot;https://stackoverflow.com/questions/28139259/why-do-we-need-monads&quot;&gt;Why Do We Need Monads?, Stack Overflow&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;</content><author><name></name></author><summary type="html">Why we need monads, what they are and where we can see them.</summary></entry></feed>