tag:blogger.com,1999:blog-79054688234374335962018-08-28T12:05:40.683-07:00antiselfdualScala, functional programmingMark Hopkinsnoreply@blogger.comBlogger1125tag:blogger.com,1999:blog-7905468823437433596.post-23668924964171028102013-06-25T06:34:00.003-07:002013-06-25T06:34:58.722-07:00Much ado about monoids<div dir="ltr" style="text-align: left;" trbidi="on">I was inspired by Tim Docker's recent illuminating talk on <a href="http://twdkz.wordpress.com/2013/05/31/data-analysis-with-monoids/">Data analysis with monoids</a>at Syd-FP, to look closer at his approach. He used Haskell for his implementation, how would things work out if I used Scala for mine? <br /><div style="background-color: #444444; border: 1px solid #eee; margin: 1em; padding: 1em;"><strong>Note:</strong> I gave a presentation on this subject at <a href="http://www.meetup.com/scalasyd/">ScalaSyd</a>; slides are available <a href="http://mjhopkins.github.io/presentations/muchAdoAboutMonoids.html">here</a>. </div>Here's the idea. We're given a CSV file of stock exchange data, looking something like this: <br /><br /><pre>20091230,GOOG,618.07,622.73,618.01,622.73,14663<br />20091231,GOOG,624.86,625.4,619.98,619.98,12202<br />20100104,GOOG,627.46,629.51,624.24,626.75,19579<br />20100105,GOOG,627.84,627.84,621.54,623.99,30078<br />20100106,GOOG,625.08,625.86,606.36,608.26,39806<br />...<br /></pre><pre></pre><br />The columns here are date, ticker symbol, opening price, highest price in the course of the day, lowest price, closing price, and volume of shares traded in the day.<br /><br />We want to perform some analysis on this data, say filter by ticker symbol, and output traded price range and count of shares traded, month by month. And it's a big file, so we want to do this in a single pass.<br /><br />Lets have a look at how we might approach this using a functional style in Scala, stopping in for a scenic tour of some useful concepts along the way, to give a hint of the possibilities inherent in this approach.<br /><br /><h4 style="text-align: left;">Monoids (and semigroups)</h4><br />We're going to need the concept of a <strong>monoid</strong> for what follows. Let's take a look.<br />Look at the following examples, and notice what's similar in each case.<br /><ol style="text-align: left;"><li><pre class="console">scala> (1 + 2) + 3 == 1 + (2 + 3)<br />res0: Boolean = true<br /><br />scala> 9 + 0<br />res1: Int = 9<br /><br />scala> 0 + 9<br />res2: Int = 9<br /></pre><br /></li><li><pre class="console">scala> ("philip" + "k") + "dick" == "philip" + ("k" + "dick")<br />res1: Boolean = true<br /><br />scala> "something" + ""<br />res2: Boolean = "something"<br /><br />scala> "" + "something"<br />res3: Boolean = "something"<br /></pre><br /></li><li><pre class="console">scala> BigInt(30) gcd (BigInt(42) gcd BigInt(70))<br />res0: scala.math.BigInt = 2<br /><br />scala> (BigInt(30) gcd (BigInt(42)) gcd BigInt(70)<br />res1: scala.math.BigInt = 2<br /><br />scala> BigInt(345) gcd BigInt(0)<br />res2: scala.math.BigInt = 345<br /><br />scala> BigInt(0) gcd BigInt(345)<br />res3: scala.math.BigInt = 345<br /></pre></li></ol>What's similar in each case? In each case we've got <br /><ol><li>a way of sticking two things of the same type together to get something else of that type: this is the operation of addition of integers, concatenation of strings, or greatest common divisor,</li><li>we've got an element that doesn't do anything when you stick it onto anything (from either side),</li><li>and we have the property that if we're sticking together a few things, it doesn't matter where we put the brackets, we still end up with the same result. <br />In other words, the final result is independent of the way we "associate" the elements together, providing we keep them in the same order. This property is called "associativity". </li></ol>Monoids are an abstraction of this common pattern, and the above paragraph is the definition of a monoid. The neutral element is usually called the "unit" of the monoid. If we don't require a unit, then we say we just have a "semigroup" rather than a monoid.<br /><br />So, where does the name come from? Well, "mono" stands for "one", because it's a gadget with only one operation. And <a href="http://en.wikipedia.org/wiki/Nicholas_Bourbaki">Nicholas Bourbaki</a>, who came up with the name and popularised the concept, liked names that end in "-oid", I guess.<br /><h4></h4><h4>Monoids and semigroups are ubiquitous</h4><br />Once you grasp the general idea, you start seeing them everywhere. Let's think of some more examples!<br /><ul style="text-align: left;"><li><code>+</code> for Int, Short, Long Double, Float, BigInt and BigDecimal with 0 as the unit</li><li><code>*</code> for Int, Short, Long, Double, Float, BigInt and BigDecimal with 1 as the unit</li><li><code>||</code> for Boolean with <code>false</code> as the unit</li><li><code>&&</code> for Boolean with <code>true</code> as the unit</li><li>greatest common divisor (for Int, Short, Long or BigInt), with 0 as the unit</li><li>lowest common multiple (for Int, Short, Long or BigInt), with 1 as the unit</li><li>maximum of two numbers.</li><li>minimum of two numbers.These last two aren't naturally a monoid, because it's not obvious what the unit should be. What's the maximum of zero numbers? We'll see below what possible workarounds we have up our sleeves if we do want a monoid.<br /> </li><li>set union, with the empty set as unit</li><li>set intersection on subsets of a Set S, with S as unit</li><li>functions from A to A, for some type A. This is what people like on call "endofunctions on A". "Endo" is just Greek for "within", because the function never takes values outside of A. The operation is function composition, and the identity function a =>a provides the unit. This is in a sense the archetypal monoid. Especially for functional programmers.</li><li>for any monoid M, we can make a monoid of out functions A => M by borrowing the monoid structure on M, i.e. <pre class="brush: scala">implicit def pointwiseMonoid[A, M](implicit m: Monoid[M]) = new Monoid[A => M] {<br /> def zero = a => m.zero<br /><br /> def append(f1: A => M, f2: A => M): A => M = a => m.append(f1(a), f2(a))<br /> }<br /></pre>Here I'm using scalaz's Monoid type class, which calls the unit "zero" and the operation "append". </li><li>we can "compose" monoids by doing them side by side. That is, by tupling them together. Here's an example: <pre class="console">scala> ("hi", List(3, 4, 5)) |+| (" Mum", List(7, 8, 9))<br />res0: (String, List[Int]) = (hi Mum,List(3, 4, 5, 7, 8, 9))<br /></pre>The <code>|+|</code> function here is just scalaz syntactic sugar for <code>append</code>. </li><li>convolution of functions. There may not be a unit, depending on the definition of convolution you use</li><li>concatentation of lists, with the empty list as unit</li><li>joining images of the same height together to make a new image, with the empty image as the unit. Or the same thing vertically.</li><li>an operation on numbers that works like this: 123 ⊹ 456 = 123456. This seems a little silly at first, but the equivalent in base 16 version is handy for chunking together binary data, and the binary version is useful when dealing with bit flags. Note that we can't define a unit for this operation, so this is only a semigroup.</li><li>Scalaz defines a monoid instance for its <code>Ordering</code> class, which consists of the values <code>EQ</code>, <code>LT</code> and <code>GT</code>. <code>append</code> is defined so that <code>x |+| y == x</code> when <code>x</code>is <code>LT</code> or <code>GT</code>, but <code>EQ |+| y == y</code>. This allows us to write chained comparisons with immaculate ease. For example, if we wanted to sort Twitter users by number of followers, then by number of tweets, then by name, we could use <pre class="brush: scala">def compareUsers(a: User, b: User): Ordering = <br /> (a.followers ?|? b.followers) |+| (a.tweets ?|? b.tweets) |+| (a.name ?|? b.name)<br /></pre>Note: <code>?|?</code> is just a little more scalaz syntactic sugar: <pre class="console">scala> 10 ?|? 12<br />res0: scalaz.Ordering = LT<br /></pre></li></ul>As an aside, you might observe that List doesn't actually do anything with the values that have been appended - they just sit in there, and you can get them out again if you want. Intuitively, this is what qualifies List to be the "free monoid". We can go in the other direction here, too, and deliberately clobber the arguments to <code>append</code>. This leads us to <br /><ul><li>this odd operation: x ⊹ y = y, ie. we throw away the left operand. Clearly, if the type has more than one member we won't be able to define a unit, so this is again only a semigroup. We might call this the "retain last" semigroup. In parallel there's a "retain first" semigroup.</li><li>the trivial monoid on type T. Choose any z of type T and define x ⊹ y = z, eg. on Int we might have x ⊹ y = 0. This operation discards both operands.</li></ul>Phew! That's a lot of monoids. Hopefully your brain is now abuzz with possibilities, and you've come up with another half a dozen more examples yourself.<br /><h4></h4><h4>What's the point?</h4><br />The advantage of recognising and naming a recurring pattern, apart from clarifying for ourselves and others the essence of what we're doing, is we can reduce the amount of boilerplate we need to write. In this case the grunt work of actually doing the accumulation: we just specify the monoid we want, and let it perform the accumulation. In addition we can take advantage of library code written for any monoid, and by writing code that's parametrized by monoid we get a lot of power for free. <br /><br />Put another way, monoids and semigroups abstract the idea of accumulation, and find a natural home any time there's some kind of combining or reduction operation going on. They allow us to clump together any number of values into one: <br /><ul><li>if we've got no values, use the unit.</li><li>if we've got one only value, great, we're done.</li><li>if we've got two values, we combine them with append</li><li>if we've got more than two, reduce in steps using append. Associativity gives us some leeway in how we choose to do this.</li></ul>You can probably see there's a natural parallel here between non empty structures, semigroups, and <code>reduce</code>on the one hand, and possibly empty structures, monoids, and <code>fold</code>. These considerations lead us on to...<br /><br /><h3 style="text-align: left;">Foldable</h3><br />Consider the fold method exposed by Scala's collection classes (for our purposes, either foldLeft or foldRight will do). Here's the signature of foldLeft defined on TraversableOnce[A], the root of Scala's collection hierarchy: <br /><br /><pre class="brush: scala">def foldLeft[B](z: B)(op: (B, A) => B): B<br /></pre><br />Now in the majority of use cases there's a monoid waiting to be discovered here. <code>z</code> is not any old value: it's the unit of a monoid, and <code>op</code> is not any old function, it's our monoid's operation in disguise. That is, we could refactor to use this method instead: <br /><br /><pre class="brush: scala">def foldMap[B](f: A => B)(implicit F: Monoid[B]) =<br /> foldLeft[B](F.zero){ case (b, a) => F.append(b, f(a)) }<br /></pre><br />Now our code that uses foldMap is a little cleaner, as we only need one parameter, and don't have to manage the accumulation ourselves.<br /><br /><h4></h4><h4>Explaining the name</h4><br />Why did we call our new operation "<code>foldMap</code>"? Well, think of the <code>flatMap</code> method: it's equivalent to first performing a <code>map</code>, and then a <code>flatten</code> on the resulting structure.<br /><br />In much the same way, <code>foldMap</code> is conceptually equivalent to first performing a <code>map</code>, and then a <code>fold</code> to combine the resulting collection of monoid values into one.<br /><br />The Scala standard library doesn't provide <code>foldMap</code>, but we can find an implementation in scalaz's <code>Foldable</code> type class, along with a number of other methods. Scalaz provides instances of <code>Foldable</code> for subclasses of <code>Iterable</code>, as well as for many scalaz data structures.<br /><br />Aside: somewhat perplexingly, it doesn't provide instances of <code>Foldable</code> for all subclasses of <code>TraversableOnce</code> (the root of Scala's collection classes).This means in particular we'll have to write our own Foldable instance to be able to use it with views (lazy versions of collections).<br /><h4><br /></h4><h4>A problem</h4><br />One obvious thing we might like to do is to average our prices, but we face a problem. Taking the mean does not form a monoid - if you give me two averages, I can't combine them unless I know the respective sizes of the datasets they were calculated from.<br /><br />But the mean is the ratio of total and count, which <b>are</b> both monoidal.<br /><br />So I could accumulate values using something along the lines of<br /><pre class="brush:scala">case class Mean[N: Fractional](sum: N, count: Int)<br /></pre>which has a natural monoid structure as the product (i.e. tuple) of two monoids, and then finally extract the mean using<br /><pre class="brush:scala">def mean = sum / fromInt(count)<br /></pre>I've parametrised over the exact type <code>N</code> here, so I don't have to write a separate version for Double, BigDecimal, etc, but I need <code>N</code> to belong to the <code>Fractional</code> type class so I can make use of division when calculating the mean. <br /><br /></div>In Part II I'll look at how we can take these ideas further, and come back to tackling our original problem. Or, if you can't wait, check out the <a href="http://mjhopkins.github.io/presentations/muchAdoAboutMonoids.html">slides</a>.Marknoreply@blogger.com0