<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/the-magrittr-monad/"></div></div><div><a data-url="https://www.r-bloggers.com/the-magrittr-monad/" data-counturl="https://www.r-bloggers.com/the-magrittr-monad/" data-count="horizontal" data-text="The magrittr monad" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.win-vector.com/blog/2016/08/the-magrittr-monad/"> R – Win-Vector Blog</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Monads are a formal theory of composition where programmers get to invoke some <em>very</em> abstract mathematics (category theory) to argue the minutia of annotating, scheduling, sequencing operations, and side effects. On the positive side the monad axioms are a guarantee that related ways of writing code are in fact substitutable and equivalent; so you want your supplied libraries to obey such axioms to make your life easy. On the negative side, the theory is complicated.</p>
<p>In this article we will consider or mad “programming theory in <a target="_blank" href="https://cran.r-project.org/">R</a> series” (see <a target="_blank" href="http://www.win-vector.com/blog/2016/01/some-programming-language-theory-in-r/">Some programming language theory in R</a>, <a target="_blank" href="http://www.win-vector.com/blog/2014/04/you-dont-need-to-understand-pointers-to-program-using-r/">You don’t need to understand pointers to program using R</a>, <a target="_blank" href="http://www.win-vector.com/blog/2015/03/using-closures-as-objects-in-r/">Using closures as objects in R</a>, and <a target="_blank" href="http://www.win-vector.com/blog/2015/04/how-and-why-to-return-functions-in-r/">How and why to return functions in R</a>).</p>
<p><span></span></p>
<p>In practice the programming language Haskell improved greatly when non-monadic I/O libraries were replaced by better monad inspired I/O libraries. But this also created the unfortunate false impression you had to understand monads to use Haskell (when in fact you only have to understand them to implement Haskell).</p>
<p>The fun side of Monads is flexibility in using them and occasionally saying (either formally or informally) “hey, x turns out to be a monad!”</p>
<p>This can vary from meaning:</p>
<ul>
<li>“x is nice (and not in fact a monad).”</li>
<li>“x is cryptomorphic to a monad (a term favored by mathematician Gian-Carlo Rota).”</li>
<li>“I went to graduate school!”</li>
<li>“Or x really obeys the monad laws.”</li>
</ul>
<p>Saying “x is a monad” is like singing in the shower, it is always more fun to say than to hear. I know I am certainly guilty of this in writing this article.</p>
<p>It turns out the <a target="_blank" href="https://cran.r-project.org/package=magrittr"><code>magrittr</code></a> pipe package in <a target="_blank" href="https://cran.r-project.org/">R</a> obeys the monad axioms. So if you are a data scientist who has tried <code>magrittr</code> you have already benefited from monadic design.</p>
<p>Obviously I am nowhere near the first to notice this, but it is something I wish to comment on here. It doesn’t matter if this is core intent or a side-effect of good design, but it does give yet another reason to trust the package.</p>
<p>Let’s load the <code>magrittr</code> package and spot-check the monad laws.</p>
<pre><code>library('magrittr')

# Identity function,
ret &lt;- function(x) { x }

# Note the example functions included here are not fully &quot;standard non-standard eval&quot;
# production hardened.</code></pre>
<p>First we check that <code>magrittr</code>’s <code>%>%</code> operator obeys the <a target="_blank" href="https://wiki.haskell.org/Monad_laws">Monad laws</a> when using <code>%>%</code> as “bind” and <code>ret</code> as “return”. For simplicity we would like to think of <code>magrittr</code> as a category over single argument functions (though obviously <code>magrittr</code> works over more values than these, and the big part of the the <code>magrittr</code> service is <a target="_blank" href="https://en.wikipedia.org/wiki/Currying">Currying</a> code fragments into single argument functions).</p>
<pre><code>a &lt;- 1:5 # our values
m &lt;- 1:5 # more values
f &lt;- sin # our first function
g &lt;- cos # our other function</code></pre>
<ul>
<li>Axiom 1 Left identity: <code>ret(a) %>% f == f(a)</code>:</li>
</ul>
<pre><code>ret(a) %>% f</code></pre>
<pre><code>## [1]  0.8414710  0.9092974  0.1411200 -0.7568025 -0.9589243</code></pre>
<pre><code>f(a)</code></pre>
<pre><code>## [1]  0.8414710  0.9092974  0.1411200 -0.7568025 -0.9589243</code></pre>
<ul>
<li>Axiom 2 Right identity: <code>m %>% ret == m</code>:</li>
</ul>
<pre><code># 
m %>% ret</code></pre>
<pre><code>## [1] 1 2 3 4 5</code></pre>
<pre><code>m</code></pre>
<pre><code>## [1] 1 2 3 4 5</code></pre>
<ul>
<li>Axiom 3 Associativity: <code>(m %>% f) %>% g == m %>% (function(x) {f(x) %>% g})</code>:</li>
</ul>
<pre><code>(m %>% f) %>% g</code></pre>
<pre><code>## [1] 0.6663667 0.6143003 0.9900591 0.7270351 0.5744009</code></pre>
<pre><code>m %>% (function(x) {f(x) %>% g})</code></pre>
<pre><code>## [1] 0.6663667 0.6143003 0.9900591 0.7270351 0.5744009</code></pre>
<p>Let’s go through those rather abstract axioms again and specialize them using our knowledge that “<code>ret</code>” is the identity.</p>
<ul>
<li>Axiom 1’ Left identity: <code>a %>% f == f(a)</code>. Says: “piping a value into a function is the same as applying the function to the value.” In general the original says <code>ret</code> has to be faithful in the sense that <code>%>%</code> can recover enough information to compute <code>f(a)</code>.</li>
<li>Axiom 2 Right identity: <code>m %>% ret == m</code>. Now implied by Axiom 1’. But in the cases where we don’t have <code>ret</code> is the identity this would tell us that <code>%>%</code> is faithful in the sense it is retaining enough information about <code>m</code> that <code>ret</code> can re-build <code>m</code>.</li>
<li>Axiom 3 Associativity: <code>(m %>% f) %>% g == m %>% (function(x) {f(x) %>% g})</code>. There is a notational convention hidden in this statement: we assume <code>m %>% f %>% g</code> is to be read as <code>(m %>% f) %>% g</code>. The axiom plus the convention tell us we can consider piping as moving the value <code>m</code> through <code>f</code> and then through <code>g</code>. This is where we are really checking <code>%>%</code> is behaving like a pipe.</li>
</ul>
<p>As a user we would like to be able to write “<code>a %>% (f %>% g)</code>” or “<code>h &lt;- f %>% g; a %>% h</code>”. That is: we would like to be able to save complex magrittr pipe sequences for re-use. We would like to have right-associativity (reified composition of operators) in addition to the left association we expect from <code>magrittr</code> being described a “forward-pipe operator” (from <a target="_blank" href="https://cran.r-project.org/package=magrittr">magrittr’s description</a>).</p>
<p>It turns out that isn’t one of the monad axions, and we can’t immediately do that:</p>
<pre><code>h &lt;- f %>% g</code></pre>
<pre><code>## Error in g(.): non-numeric argument to mathematical function</code></pre>
<p>We can fix this one of two ways: by introducing a function or using a built-in “dot notation” (thank you to Professor Jenny Bryan <a target="_blank" href="https://twitter.com/JennyBryan/status/761431075318960128">for pointing this out to me</a>.)</p>
<pre><code>h &lt;- function(x) { x %>% f %>% g }
a %>% h</code></pre>
<pre><code>## [1] 0.6663667 0.6143003 0.9900591 0.7270351 0.5744009</code></pre>
<pre><code>h &lt;- . %>% f %>% g
a %>% h</code></pre>
<pre><code>## [1] 0.6663667 0.6143003 0.9900591 0.7270351 0.5744009</code></pre>
<p>It turns out category theorists anticipated this problem and fix. The function wrapping trick is essentially building the Kleisli category derived from our monad (see <a target="_blank" href="http://www.stephendiehl.com/posts/monads.html">“Monads Made Difficult”</a>).</p>
<p>In principle we could implement a Kleisli arrow <code>%>=>%</code> operator in addition to the <code>magrittr</code> bind operator (<code>%>%</code>) which would allow code like the following (all four statements below would be equivalent):</p>
<pre><code>`%>=>%` &lt;- function(f,g) { function(x) {g(f(x))} }
a %>% (sin %>=>% cos %>=>% abs)</code></pre>
<pre><code>## [1] 0.6663667 0.6143003 0.9900591 0.7270351 0.5744009</code></pre>
<pre><code>a %>% ((sin %>=>% cos) %>=>% abs)</code></pre>
<pre><code>## [1] 0.6663667 0.6143003 0.9900591 0.7270351 0.5744009</code></pre>
<pre><code>a %>% (sin %>=>% (cos %>=>% abs))</code></pre>
<pre><code>## [1] 0.6663667 0.6143003 0.9900591 0.7270351 0.5744009</code></pre>
<pre><code>abs(cos(sin(a)))</code></pre>
<pre><code>## [1] 0.6663667 0.6143003 0.9900591 0.7270351 0.5744009</code></pre>
<p>Note that the above <code>%>=>%</code> operator is <em>not</em> in fact the desired general Kleisli operator as we haven’t implemented the critical Currying services that the <code>magrittr</code> <code>%>%</code> operator supplies (these services would be what category theorist call the “endofunctor” which would map R functions to specialized savable R functions; definitions such as <code>function(f,g) { . %>% f %>% g }</code> won’t work either as we would need to capture unevaluated arguments inside the <code>%>=>%</code> function and can not delegate that to interior <code>%>%</code> calls).</p>
<p>In the Kleisli category we would no longer need special monad axioms, they are replaced by the more common associativity and category axioms in the Kleisli category. One still has to prove you have a category, but it is a more standard task.</p>
<p>You can say standard imperative styles of analysis that see operations as sequenced transient steps that mutate data are “strict left to right associative” ways of thinking (the “<code>((a %>% sin) %>% cos) %>% abs</code>” form). Databases, and standard data analyses in <code>R</code> are usually so organized.</p>
<p>The “general associativity” way of thinking (the “<code>h &lt;- sin %>=>% cos %>=>% abs; a %>% h</code>” form) emphasizes the processing pipeline as a reusable entity and data a transient quantities that flow through the pipeline. Systems like <a target="_blank" href="http://www.cs.waikato.ac.nz/ml/weka/">Weka</a>, <a target="_blank" href="http://alias-i.com/lingpipe/">LingPipe</a>, and graphical data science tools such as <a target="_blank" href="http://alpinedata.com/product/">Alpine Data workflow notebooks</a> essentially represented processes in this manner.</p>
<p><center>
<div>
<img title="TP-Workbench-e1464128399327.png" alt="TP Workbench e1464128399327" src="http://i2.wp.com/www.win-vector.com/blog/wp-content/uploads/2016/08/TP-Workbench-e1464128399327.png?w=660" border="0" data-recalc-dims="1">
<p>Analysis steps as a durable graph: Alpine Data workflow notebooks</p>
</div>
<p></p>
<p>The guarantee of full associativity is just a mathematical way of saying: you can mix these styles (data oriented or operator oriented) <em>and</em> you are guaranteed the same result in either case.</p>
<p>And there you have it, more category theory than a data scientist should need to worry about.</p>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/the-magrittr-monad/"></div></div><div><a data-url="https://www.r-bloggers.com/the-magrittr-monad/" data-counturl="https://www.r-bloggers.com/the-magrittr-monad/" data-count="vertical" data-text="The magrittr monad" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.win-vector.com/blog/2016/08/the-magrittr-monad/"> R – Win-Vector Blog</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/um-LhTLFpes"></a></div></center>