<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.9.0">Jekyll</generator><link href="http://dilyand.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="http://dilyand.github.io/" rel="alternate" type="text/html" /><updated>2022-01-07T17:13:12+00:00</updated><id>http://dilyand.github.io/feed.xml</id><title type="html">Random Acts of Software Development</title><subtitle>A journal of my peripatetic journeys in code</subtitle><author><name>Dilyan Damyanov</name></author><entry><title type="html">Why is Monoid?</title><link href="http://dilyand.github.io/why-is-monoid/" rel="alternate" type="text/html" title="Why is Monoid?" /><published>2022-01-07T00:00:00+00:00</published><updated>2022-01-07T00:00:00+00:00</updated><id>http://dilyand.github.io/why-is-monoid</id><content type="html" xml:base="http://dilyand.github.io/why-is-monoid/">&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Monoid&lt;/code&gt; is fairly easy to understand, even if you’re just starting out in functional programming. First, you need to understand what a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Semigroup&lt;/code&gt; is. The Cats definition is very accessible:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;If a type &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;A&lt;/code&gt; can form a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Semigroup&lt;/code&gt; it has an associative binary operation.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;trait Semigroup[A] {
  def op(x: A, y: A): A
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And associativity means that elements can be combined using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;op&lt;/code&gt; in random order:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;op(a, op(b, c)) == op(op(a, b), c)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The classic example is the addition of integers:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;val sumInt: Semigroup[Int] = new Semigroup {
  def op(x: A, y: A): A = x + y
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;op&lt;/code&gt; binary operator of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sumInt&lt;/code&gt; is associative because &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(1 + (2 + 3)) = ((1 + 2) + 3)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;By contrast, subtraction of integers is not a valid example of a semigroup, because even though the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-&lt;/code&gt; operator is binary, it is not associative: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(3 - (2 - 1)) =/= ((3 - 2) - 1)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now that we understand &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Semigroup&lt;/code&gt;, we can introduce &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Monoid&lt;/code&gt;. To borrow from Cats again:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Monoid&lt;/code&gt; extends the power of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Semigroup&lt;/code&gt; by providing an additional empty value.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;trait Monoid[A] extends Semigroup[A] {
  def id: A
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The empty value, also known as ‘identity’ value, is such that when used in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;op&lt;/code&gt;, the output is no-op.&lt;/p&gt;

&lt;p&gt;For example, addition of integers forms a monoid, because not only is its binary operation associative, but it also has &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; as the identity element: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1 + 0 = 1&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Other monoid examples include multiplication of integers (with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;id&lt;/code&gt; of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt;) and concatenation of strings (with the empty string &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;&quot;&lt;/code&gt; as identity element).&lt;/p&gt;

&lt;p&gt;When you read about these concepts through the lens of functional programming or mathematics / category theory, it’s easy to be left with the impression that things like semigroup and monoid just &lt;em&gt;exist&lt;/em&gt;, and we are simply discovering and describing them. But of course there’s another way of looking at them: that they are invented by us, and we’ve invented them such as they are for a reason.&lt;/p&gt;

&lt;p&gt;So what is the reason that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Semigroup&lt;/code&gt; must have an associative operator? And why does &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Monoid&lt;/code&gt; need an identity element?&lt;/p&gt;

&lt;p&gt;To understand this, let’s look at an example.&lt;/p&gt;

&lt;p&gt;Take a nested list of values, like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;List(List(1, 2, 3), List(4, 5))&lt;/code&gt;. We might want to collapse this into a single value, by applying some operation to the values in each inner list, and then combining the intermediate results using the same operation. For example, maybe we want to calculate the total sum. So first, we’d want to sum &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;3&lt;/code&gt;; then we’d want to sum &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;4&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5&lt;/code&gt;; and finally we’d want to sum the results of these calculations to get a total of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;15&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We might also want to make this function generic, so that it works not only with integers and addition, but any value &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;A&lt;/code&gt; and any operation that takes two &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;A&lt;/code&gt;s and returns an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;A&lt;/code&gt;. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldLeft&lt;/code&gt; seems a good choice for implementing this function, which means we’ll also need a default value:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;def func[A](l: List[List[A]], default: A)(combine: (A, A) =&amp;gt; A) =
  l.map(_.foldLeft(default)(combine)).foldLeft(default)(combine)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This seems to work fine for calculating the sum of integers, and we can see that it produces the same result as flattening the list and then adding all the values together:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;val l = List(List(1, 2, 3), List(4, 5))

func(l, 0)(_ + _)
// 15: Int

l.flatten.foldLeft(0)(_ + _)
// 15: Int
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;But what if instead of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;, we chose &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-1&lt;/code&gt; as the default value?&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;func(l, 1)(_ + _)
// 18: Int

l.flatten.foldLeft(1)(_ + _)
// 16: Int

func(l, -1)(_ + _)
// 12: Int

l.flatten.foldLeft(-1)(_ + _)
// 14: Int
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;So, for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;func(a)&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;a.flatten.foldLeft&lt;/code&gt; to have the same result, we need the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;default&lt;/code&gt; value to be such that when we use it in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;combine&lt;/code&gt; the output is a no-op. Which is the very definition of the identity function in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Monoid&lt;/code&gt;!&lt;/p&gt;

&lt;p&gt;If we wanted to simplify &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;func&lt;/code&gt;, we could abstract the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;default&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;combine&lt;/code&gt; parameters into some structure, and that structure would be a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Monoid&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;def func[A](l: List[List[A]])(m: Monoid[A]) =
  l.map(_.foldLeft(m.id)(m.op)).foldLeft(m.id)(m.op)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In other words, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Monoid&lt;/code&gt; &lt;em&gt;needs&lt;/em&gt; an identity function, so that it can be used for operations like the one in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;func&lt;/code&gt;: where we apply some &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;combine&lt;/code&gt; function first to the inner members of a nested structure, then on the results from the first pass.&lt;/p&gt;

&lt;p&gt;And why does &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;op&lt;/code&gt; need to be associative?&lt;/p&gt;

&lt;p&gt;If we think about where we might have nested structures like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;List(List(1, 2, 3), List(4, 5))&lt;/code&gt;, one frequent use case is in parallel computing. We might start with a very big collection of some values, and instead of going through it element by element, we might want to first break it into multiple smaller collections, which can then be processed in parallel. The intermediate results are ultimately combined together. (An example of this is &lt;a href=&quot;https://en.wikipedia.org/wiki/MapReduce&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MapReduce&lt;/code&gt;&lt;/a&gt;.)&lt;/p&gt;

&lt;p&gt;The thing is, if we started with a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;List(1, 2, 3, 4, 5)&lt;/code&gt; and wanted to apply a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MapReduce&lt;/code&gt;, we’re not guaranteed to get the data partitioned as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;List(List(1, 2, 3), List(4, 5))&lt;/code&gt;. It might be &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;List(List(1, 2), List(3, 4, 5))&lt;/code&gt;. Addition of integers is an associative operation but if we instead apply a non-associative one, we see that the result is different, depending on how the data was partitioned initially:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;val l1 = List(List(1, 2, 3), List(4, 5))
val l2 = List(List(1, 2), List(3, 4, 5))

func(l1, 0)((f, s) =&amp;gt; (f + s) / 2)
// 2: Int

func(l2, 0)((f, s) =&amp;gt; (f + s) / 2)
// 1: Int
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;So, in order for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MapReduce&lt;/code&gt; to work with multiple ‘reducers’ in parallel, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;reduce&lt;/code&gt; function needs to be associative, to guarantee the same result, regardless of the order in which partitions are reduced.&lt;/p&gt;</content><author><name>Dilyan Damyanov</name></author><category term="Scala" /><category term="Monoid" /><category term="MapReduce" /><summary type="html">Monoid is fairly easy to understand, even if you’re just starting out in functional programming. First, you need to understand what a Semigroup is. The Cats definition is very accessible:</summary></entry><entry><title type="html">F[A] is ‘F of A’ but what is asRight[A]?</title><link href="http://dilyand.github.io/f-of-a-vs-asright-of-a/" rel="alternate" type="text/html" title="F[A] is ‘F of A’ but what is asRight[A]?" /><published>2021-06-11T00:00:00+00:00</published><updated>2021-06-11T00:00:00+00:00</updated><id>http://dilyand.github.io/f-of-a-vs-asright-of-a</id><content type="html" xml:base="http://dilyand.github.io/f-of-a-vs-asright-of-a/">&lt;p&gt;A few times I’ve fallen into the trap of making incorrect assumptions about what a type is based on how I read it in my head. Most recently, this happened with the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;asRight&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;asLeft&lt;/code&gt; wrappers of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cats.Either&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Lo:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;import cats.implicits._

case class Bad(i: Int)
case class Good(i: Int)
type Parsed = Either[Bad, Good]

def check(value: Int): Parsed =
  if (value &amp;gt;= 0) Good(value).asRight[Bad] else Bad(value).asLeft[Good]

check(0)
// val res0: Parsed = Right(Good(0))

check(1)
//val res1: Parsed = Right(Good(1))

check(-34644425)
// val res2: Parsed = Left(Bad(-34644425))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;At first glance, I was surprised that it compiles, because it appeared that in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;check&lt;/code&gt; function we’re wrapping the results the wrong way around: the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Good&lt;/code&gt; results as a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Bad&lt;/code&gt; and vice versa.&lt;/p&gt;

&lt;p&gt;Of course, it’s clear from the signatures of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;asRight&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;asLeft&lt;/code&gt; that it’s not the case:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  /**
   * Wrap a value in `Left`.
   */
  def asLeft[B]: Either[A, B] = Left(obj)

  /**
   * Wrap a value in `Right`.
   */
  def asRight[B]: Either[B, A] = Right(obj)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The type parameter &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;B&lt;/code&gt; in either case is the type of the value that goes on the ‘opposite’ side of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Either&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;It makes sense, if you think about it. The wrapper already knows what type the wrapped value has because it has access to it. The information that it is missing is what the alternative is.&lt;/p&gt;

&lt;p&gt;The reason for my confusion is that in my head when I read the code of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;check&lt;/code&gt; it goes like this: “If the value is greater than or equal to zero then create an instance of Good with the value and wrap it in a Right of Bad, otherwise create an instance of Bad and wrap it a Left of Good.” These ‘Right of Bad’ and ‘Left of Good’ are a natural extension of the reading ‘F of A’ when faced with an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;F[A]&lt;/code&gt;. But they are misleading in this case. In this case, the proper reading is actually ‘Right with a Left of Bad’ / ‘Left with a Right of Good’.&lt;/p&gt;

&lt;p&gt;A more intuitive signature for the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;asRight&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;asLeft&lt;/code&gt; wrappers would be something along the lines of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;asEither[Left, Right]&lt;/code&gt;, which has its own downsides.&lt;/p&gt;</content><author><name>Dilyan Damyanov</name></author><category term="Scala" /><category term="Either" /><category term="Left" /><category term="Right" /><summary type="html">A few times I’ve fallen into the trap of making incorrect assumptions about what a type is based on how I read it in my head. Most recently, this happened with the asRight and asLeft wrappers of cats.Either.</summary></entry><entry><title type="html">Should `flatMap` be called `mapFlat`?</title><link href="http://dilyand.github.io/flatMap-should-be-called-mapFlat/" rel="alternate" type="text/html" title="Should `flatMap` be called `mapFlat`?" /><published>2021-03-12T00:00:00+00:00</published><updated>2021-03-12T00:00:00+00:00</updated><id>http://dilyand.github.io/flatMap-should-be-called-mapFlat</id><content type="html" xml:base="http://dilyand.github.io/flatMap-should-be-called-mapFlat/">&lt;p&gt;The name of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;flatMap&lt;/code&gt; might trick you into thinking that it is the same as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;flatten&lt;/code&gt; followed by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;map&lt;/code&gt;. But it’s exactly the other way around: it’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;map&lt;/code&gt; followed by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;flatten&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Behold:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;List(List(1, 2, 3), List(4, 5, 6)).flatten.map(_ + 1)
// res5: List[Int] = List(2, 3, 4, 5, 6, 7)

List(List(1, 2, 3), List(4, 5, 6)).flatMap(_ + 1)
// If _.flatMap(f) was the same as _.flatten.map(f), this should work in the same way.
// Instead, we get:
//  type mismatch;
//  found   : Int(1)
//  required: String
//  List(List(1, 2, 3), List(4, 5, 6)).map(_ + 1).flatten

List(List(1, 2, 3), List(4, 5, 6)).map(_ + 1).flatten 
// Same result as with flatMap: 
//  type mismatch;
//  found   : Int(1)
//  required: String
//  List(List(1, 2, 3), List(4, 5, 6)).map(_ + 1).flatten

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;For &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;flatMap&lt;/code&gt; to work in this example, it needs to be passed a function that can be applied to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;List&lt;/code&gt;, eg:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;List(List(1, 2, 3), List(4, 5, 6)).flatMap(0 :: _)
// res6: List[Int] = List(0, 1, 2, 3, 0, 4, 5, 6)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;But not something that reduces the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;List&lt;/code&gt; to an un-flattenable value:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;List(List(1, 2, 3), List(4, 5, 6)).flatMap(_.sum)
// type mismatch;
// found   : Int
// required: scala.collection.GenTraversableOnce[?]
// List(List(1, 2, 3), List(4, 5, 6)).flatMap(_.sum)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;</content><author><name>Dilyan Damyanov</name></author><category term="Scala" /><category term="flatMap" /><summary type="html">The name of flatMap might trick you into thinking that it is the same as flatten followed by map. But it’s exactly the other way around: it’s map followed by flatten.</summary></entry><entry><title type="html">Beware `java.nio.ByteBuffer` mutability</title><link href="http://dilyand.github.io/beware-bytefbuffer-mutability/" rel="alternate" type="text/html" title="Beware `java.nio.ByteBuffer` mutability" /><published>2021-03-02T00:00:00+00:00</published><updated>2021-03-02T00:00:00+00:00</updated><id>http://dilyand.github.io/beware-bytefbuffer-mutability</id><content type="html" xml:base="http://dilyand.github.io/beware-bytefbuffer-mutability/">&lt;p&gt;According to the documentation for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;java.nio.ByteBuffer.wrap(array)&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Wraps a byte array into a buffer.
The new buffer will be backed by the given byte array;
that is, modifications to the buffer will cause the array to be modified
and vice versa.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Every time you operate on a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ByteBuffer&lt;/code&gt;, you modify it.&lt;/p&gt;

&lt;p&gt;Here’s an example comparing how &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ByteBuffer&lt;/code&gt; behaves vs &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Array[Byte]&lt;/code&gt;. Imagine you receive binary data (such as Thrift-encoded records), which you want to process and then write to a message queue.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;import java.nio.ByteBuffer

// a single record received from upstream
val msgBytes: Array[Byte] = &quot;I am a test message.&quot;.getBytes()

// the same record wrapped in a ByteBuffer
val msgBuff: ByteBuffer = ByteBuffer.wrap(msgBytes)

// scenario A: a stream of records wrapped in a ByteBuffer
val batchA = List.fill(3)(msgBuff)
val resultA = batchA.map(m =&amp;gt; new String(java.util.Base64.getEncoder.encode(m).array))
println(resultA) // List(SSBhbSBhIHRlc3QgbWVzc2FnZS4=, , )

// scenario B: a stream of records kept as Array[Byte]
val batchB = List.fill(3)(msgBytes)
val resultB = batchB.map(m =&amp;gt; new String(java.util.Base64.getEncoder.encode(m)))
println(resultB) // List(SSBhbSBhIHRlc3QgbWVzc2FnZS4=, SSBhbSBhIHRlc3QgbWVzc2FnZS4=, SSBhbSBhIHRlc3QgbWVzc2FnZS4=)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;</content><author><name>Dilyan Damyanov</name></author><category term="Scala" /><category term="Java" /><category term="ByteBuffer" /><summary type="html">According to the documentation for java.nio.ByteBuffer.wrap(array):</summary></entry><entry><title type="html">Using `foldRight` instead of `map`</title><link href="http://dilyand.github.io/using-map-instead-of-foldright/" rel="alternate" type="text/html" title="Using `foldRight` instead of `map`" /><published>2021-02-11T00:00:00+00:00</published><updated>2021-02-11T00:00:00+00:00</updated><id>http://dilyand.github.io/using-map-instead-of-foldright</id><content type="html" xml:base="http://dilyand.github.io/using-map-instead-of-foldright/">&lt;p&gt;Say you want to implement a function &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;add1&lt;/code&gt; that takes a list of integers and adds 1 to each one, so that:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;add1(List(1, 2, 3)) == List(2, 3, 4)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This is trivial with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;map&lt;/code&gt; but can &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;add1&lt;/code&gt; be implemented in terms of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight&lt;/code&gt;?&lt;/p&gt;

&lt;p&gt;The signature of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight&lt;/code&gt; has two type parameters &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;A&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;B&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;foldRight[B](z: B)(op: (A, B) =&amp;gt; B): B
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;There is some implicit knowledge that is required here to fully understand that signature. Firstly, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;A&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;B&lt;/code&gt; can be the same type, eg an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Int&lt;/code&gt;. Secondly, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight&lt;/code&gt; operates on collections, such as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;List&lt;/code&gt;, collapsing them to a single value. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;A&lt;/code&gt; is the type of each element in the collection.&lt;/p&gt;

&lt;p&gt;If we think about turning &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;List(1, 2, 3)&lt;/code&gt; into &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;List(2, 3, 4)&lt;/code&gt;, we might fall into the trap of thinking that we need to “get into” the list and then traverse over each element in turn by applying a function to it. That is certainly what &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;map&lt;/code&gt; would do, but it is incorrect with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight&lt;/code&gt;. What &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight&lt;/code&gt; does is it traverses over the elements of the list, applying a function, but adds the result of that operation to an accumulator until ultimately all elements are processed and the final value of the accumulator is returned. This can be seen in its signature, where &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;B&lt;/code&gt; is the type returned by the function that is being applied (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;op&lt;/code&gt;) and also the return type of the outer &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight&lt;/code&gt; function. It is also the type of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;z&lt;/code&gt;, the initial value of the accumulator.&lt;/p&gt;

&lt;p&gt;So, to implement &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;add1&lt;/code&gt; in terms of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight&lt;/code&gt;, we need to collapse the original list into a single value, which in this case happens to be another list, with the same number of elements which also have the same type:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;def add1(l: List[Int]): List[Int] =
  l.foldRight(Nil: List[Int])((x, y) =&amp;gt; (x + 1)::y)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The parameter &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y&lt;/code&gt; is the accumulator. It starts at &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Nil&lt;/code&gt; and then each element of the original list is prepended to it after getting incremented by 1. Since &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight&lt;/code&gt; is not tail-recursive, it will first prepend the last element of the original list to the accumulator, then the second to last, etc.&lt;/p&gt;

&lt;p&gt;Another way to implement &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;add1&lt;/code&gt; without using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;map&lt;/code&gt; is to write a recursive function that pattern-matches the original list. The pattern-match will have two branches, one for the base case (which here would be the empty list &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Nil&lt;/code&gt;) and a recursive branch for a non-empty list:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;def add1(l: List[Int]): List[Int] = l match {
  case Nil =&amp;gt; Nil
  case h::t =&amp;gt; (h + 1)::t
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;So any time we have a pattern-match of this kind:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;l match {
  case Nil =&amp;gt; ???
  case h::t =&amp;gt; ???
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;where &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;l&lt;/code&gt; is some &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;List&lt;/code&gt;-like collection, we can replace it with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight&lt;/code&gt;. The base-case branch is what our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;z&lt;/code&gt; would be and the non-empty case branch would be &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;op&lt;/code&gt; that adds values on top of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;z&lt;/code&gt;, both ultimately returning the same type.&lt;/p&gt;</content><author><name>Dilyan Damyanov</name></author><category term="Scala" /><category term="foldRight" /><summary type="html">Say you want to implement a function add1 that takes a list of integers and adds 1 to each one, so that:</summary></entry><entry><title type="html">Naming things is hard</title><link href="http://dilyand.github.io/naming-is-hard/" rel="alternate" type="text/html" title="Naming things is hard" /><published>2021-01-24T00:00:00+00:00</published><updated>2021-01-24T00:00:00+00:00</updated><id>http://dilyand.github.io/naming-is-hard</id><content type="html" xml:base="http://dilyand.github.io/naming-is-hard/">&lt;p&gt;I recently realised that ambiguous argument naming has been a major obstacle for me building intuition about how &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight&lt;/code&gt; works in Scala.&lt;/p&gt;

&lt;p&gt;To illustrate, here’s a simplified definition of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;def foldRight[A, B](as: List[A], z: B)(f: (A, B) =&amp;gt; B): B =
  as match {
    case Nil =&amp;gt; z
    case h::t =&amp;gt; f(h, foldRight(t, z)(f))
  }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;and here’s a function implemented in terms of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;def doubleToString(l: List[Double]): List[String] =
  foldRight(l, Nil:List[String])((h, t) =&amp;gt; h.toString::t)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;(These examples come from the exercises in the awesome &lt;em&gt;Functional Programming in Scala&lt;/em&gt; by Paul Chiusano and Runar Bjarnason.)&lt;/p&gt;

&lt;p&gt;Both of these functions operate on a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;List&lt;/code&gt; and they both in some way de-structure the list to its &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;head&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tail&lt;/code&gt;. Their signatures also include arguments named &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;t&lt;/code&gt; in their inner scope. It is the naming of these arguments that is at the root of the challenge. Intuitively, when reading the definition of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;doubleToString&lt;/code&gt;, I expand &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h&lt;/code&gt; to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;head&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;t&lt;/code&gt; to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tail&lt;/code&gt;. But, while this expansion is valid for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h&lt;/code&gt; in both function definitions, it is only valid for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;t&lt;/code&gt; in the definition of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight&lt;/code&gt;. In the definition of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;doubleToString&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;t&lt;/code&gt; actually means not &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tail&lt;/code&gt; but rather &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight(tail, Nil)((head, a) =&amp;gt; head.toString::a)&lt;/code&gt;. The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;a&lt;/code&gt; in that last snippet can itself be recursively replaced with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight(a.tail, Nil)(...)&lt;/code&gt;. It is this recursion, which is part of the definition of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight&lt;/code&gt;, that causes the trouble. If all I see is the definition of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;doubleToString&lt;/code&gt;, it is not obvious to me that this recursion exists. I must remember that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight&lt;/code&gt; is a recursive function and that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;t&lt;/code&gt; in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;doubleToString&lt;/code&gt; is also recursive.&lt;/p&gt;

&lt;p&gt;My issue with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;t&lt;/code&gt; in the definition of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;doubleToString&lt;/code&gt; is that the instinctive expansion to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;head&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tail&lt;/code&gt;, drilled into me by so many other occurrences of this shorthand, prevents me from clicking through and checking the definition of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;foldRight&lt;/code&gt;. I make incorrect assumptions, which lead to incorrect interpretations.&lt;/p&gt;

&lt;p&gt;By contrast, naming the argument something like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;a&lt;/code&gt; forces me to investigate, or else I would have no idea what it is. I can no longer automatically assume that it has anything at all to do with the List &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;l&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;def doubleToString(l: List[Double]): List[String] =
  foldRight(l, Nil:List[String])((h, a) =&amp;gt; h.toString::a)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;To make it even clearer, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;a&lt;/code&gt; can be called something like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;acc&lt;/code&gt; (for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;accumulator&lt;/code&gt;), which hints at its recursive nature.&lt;/p&gt;</content><author><name>Dilyan Damyanov</name></author><category term="Scala" /><category term="foldRight" /><summary type="html">I recently realised that ambiguous argument naming has been a major obstacle for me building intuition about how foldRight works in Scala.</summary></entry></feed>