<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sinisa Louc on Medium]]></title>
        <description><![CDATA[Stories by Sinisa Louc on Medium]]></description>
        <link>https://medium.com/@sinisalouc?source=rss-690955769210------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3U1OGChR_wTdn3UQJooyxw.png</url>
            <title>Stories by Sinisa Louc on Medium</title>
            <link>https://medium.com/@sinisalouc?source=rss-690955769210------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 09:15:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sinisalouc/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scala eXchange London 2018: A topic-based approach to conferences]]></title>
            <link>https://medium.com/skills-matter/scala-exchange-london-2018-a-topic-based-approach-to-conferences-34beb3fe01e2?source=rss-690955769210------2</link>
            <guid isPermaLink="false">https://medium.com/p/34beb3fe01e2</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[conference]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[scalax]]></category>
            <dc:creator><![CDATA[Sinisa Louc]]></dc:creator>
            <pubDate>Sun, 16 Dec 2018 14:22:28 GMT</pubDate>
            <atom:updated>2019-01-17T14:08:52.008Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HG-YcbJ8lD0MLEMIVtmiCg.jpeg" /></figure><p><em>👍 For news and articles from Skills Matter, </em><a href="https://goo.gl/forms/mJch7CJU9d0T7XDP2"><em>subscribe to our newsletter here.</em></a></p><p>I just came back from London where I had the opportunity to attend <a href="https://skillsmatter.com/conferences/10488-scala-exchange-2018">Scala eXchange 2018</a> and I noticed one really interesting thing: its topic-based approach. Many conferences usually declare some kind of leitmotif, such as “in the light of upcoming Scala 3…”, but Scala eXchange really had a concrete set of topics as a recurring theme throughout the whole programme. Is this a good thing or a bad thing? Let’s see.</p><h3>To topic or not to topic</h3><p>For example, earlier this year I <a href="https://www.spotcap.com/spotcap-behind-scenes/scala-days/">said</a> that ScalaDays in Berlin contained a little bit for everyone. Which is awesome in its own right. In a wide variety of topics, you are almost guaranteed to find something that really sparks your interest. From talks about concrete tools and frameworks such as SBT, Dotty, Finagle, Spire, Akka/Kafka/Monix Streams, Spark, Akka Cluster, Akka Typed, sttp, Lagom, Bloop, Scala Native, Scala JS etc., to talks involving concepts such as literal types, variance, traversables, execution contexts, kind-polymorphism, and more general things such as graph databases, deep learning, category theory, microservices, event driven programming, domain-driven design, protocol buffers etc. (still told from a Scala perspective, of course). There was something for everyone.</p><p>However, <a href="https://skillsmatter.com/conferences/11987-scala-exchange-london-2019">Scala eXchange</a> is slightly different. It had an announced set of topics for this year: “<strong>Apache Kafka and Spark, types, Cats, and Tagless Final</strong>”. I don’t have too much interest in talks about Spark and Kafka (no hard feelings anyone), so I can’t say anything in that regard, but the “types, Cats and Tagless Final” part really delivered on its promise.</p><p>So, which is better, a-little-bit-for-everyone or a topic-based approach? It’s hard to tell. A diverse set of topics is kinda “playing it safe” and it can’t go wrong, but I really like the road that Scala eXchange took as well. Free, tagless final, recursive schemes, MTL, it all revolves around a similar theme, which I’m exploring myself at the moment, so for me it was very rewarding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9JWEW0jwdRAnZH36JQsNQ.png" /><figcaption><em>A slide from </em><a href="https://skillsmatter.com/legacy_profile/pere-villega"><em>Pere Villega</em></a><em>’s Lightning Talk: MTL in 15 minutes</em></figcaption></figure><p>And the machinery behind it was narrowed down to <a href="https://typelevel.org/cats/">Cats</a> only, which I also find convenient. I’m using Scalaz more than I’m using Cats, but that’s not a problem; I’d rather have the whole conference Cats-only, which makes the talks more cohesive (concepts are similar anyway), than constantly have them flipping between the two, which might get a bit confusing (not to mention Scalaz vs Cats flame wars).</p><p>In order to illustrate my point better, here’s the quick digest of the talks I attended:</p><p><strong>Fistful of Functors </strong>by<strong> </strong>Itamar Ravid (<a href="https://skillsmatter.com/skillscasts/12645-a-fistful-of-functors">link</a>)<strong>:</strong></p><ul><li>using Cats typeclasses for covariant, contravariant and invariant functors, bifunctors and profunctors</li><li>detailed explanation of functor composition and its usage via Nested/Binested typeclass</li></ul><p><strong>Cats Effect, Tagless Final &amp; beyond </strong>by<strong> </strong>Gabriel Volpe (<a href="https://skillsmatter.com/skillscasts/12634-cats-effect-tagless-final-and-beyond">link</a>)<strong>:</strong></p><ul><li>using <a href="https://github.com/typelevel/cats-effect">cats-effect</a> library for handling synchronous and asynchronous computations, error handling, safe resource management, concurrency, parallelism and cancellation (via IO and typeclasses such as Sync, Bracket, Concurrent, Timer, Par)</li><li>decoupling logic from interpretation by refactoring IO code into tagless final</li></ul><p><strong>Factor Recursion Out of Your Codebase </strong>by Tamer AbdulRadi (<a href="https://skillsmatter.com/skillscasts/12805-factor-recursion-out-of-your-codebase">link</a>)<strong>:</strong></p><ul><li>explanation of recursion schemes (based on <a href="https://maartenfokkinga.github.io/utwente/mmf91m.pdf">this paper</a> from 1991)</li><li>available via libraries like <a href="https://github.com/slamdata/matryoshka">matryoshka</a> and <a href="https://github.com/tpolecat/turtles">turtles</a>, but this talk relies on Cats for manual implementation via type parameters, functors and fixed-point combinator</li></ul><p><strong>Functional Composition and the Kleisli</strong> by Alexander Worton (link):</p><ul><li>composing functions, composing monads (monad transformers)</li><li>aligning the types, achieving more readability and improving testability by lifting into Kleisli (Cats)</li></ul><p><strong>Cobind and Chill </strong>by Danielle Ashley (<a href="https://skillsmatter.com/skillscasts/12743-cobind-and-chill">link</a>):</p><ul><li>explanation of usefulness of comonad structure (available as a Cats typeclass) in signal processing</li><li>implementation and demonstration of decoding of a sampled analogue TV signal</li></ul><p><strong>Why the Web is a Monad </strong>by<strong> </strong>Luke Tebbs (<a href="https://skillsmatter.com/skillscasts/13181-lightning-talk-why-the-web-is-a-monad">link</a>):</p><ul><li>user interaction as an abstract program</li><li>presents and showcases a WIP library, <a href="https://github.com/ltbs/uniform-scala">uniform-scala</a>, which allows us to define the user journey in a functional way via a DSL and let interpreters build everything for us (Web interface, GUI, CLE, static page…)</li></ul><p><strong>MTL in 15 minutes </strong>by Pere Villega (<a href="https://skillsmatter.com/skillscasts/13292-lightning-talk-mtl-in-15-minutes">link</a>):</p><ul><li>explanation of monad stacks implemented via tagless final</li><li>using library <a href="https://github.com/typelevel/cats-mtl">cats-mtl</a> for implementing monad transformer stacks via typeclasses instead of manual MTL stacking</li></ul><p><strong>Liquid Haskell: Theorem Proving for All </strong>by Niki Vazou<strong> </strong>(<a href="https://skillsmatter.com/skillscasts/13115-liquid-haskell-theorem-proving-for-all">link</a>):</p><ul><li>Liquid Haskell refines Haskell’s types with logical predicates that let us enforce critical properties at compile time</li><li>it’s a Haskell talk, but it explains the general concept of refined types which is also applicable in Scala (e.g. via <a href="https://github.com/fthomas/refined">refined</a> library); this can also be connected to dependent types, which is something I had a really nice chat with Miles Sabin about</li></ul><p><strong>Unfolding Programs With Interpreters</strong> by Regis Kuckaertz (<a href="https://skillsmatter.com/skillscasts/12833-unfolding-programs-with-interpreters">link</a>):</p><ul><li>free monad and tagless final both have the concept of algebra + interpreters; this talk shows how comonads can be used to build interpreters</li><li>contains some interesting parallels, from function application being the equivalent of modus ponens in logic, to React’s store/state being a monad/comonad pair</li></ul><p><strong>Type-Driven Development in Practice: Cats and Akka HTTP </strong>by Matt Roberts (<a href="https://skillsmatter.com/skillscasts/13003-type-driven-development-in-practice-cats-and-akka-http">link</a>):</p><ul><li>type-driven development as a programming style</li><li>using Cats Free, IO, Writer and Reader for implementing a web service in Akka HTTP</li></ul><p><strong>Functional Interpreters and You </strong>by Dave Gurnell (<a href="https://skillsmatter.com/skillscasts/12741-functional-interpreters-and-you">link</a>):</p><ul><li>explanation of algebra + interpreters concept from two viewpoints — reification and Church encoding, which correspond to free monad and tagless final respectively</li><li>example-driven showcase which takes us through the process of designing and implementing each of them, yielding a detailed comparison between the two</li></ul><p><strong>Pushing Types and Gazing at the Stars</strong> by Rob Norris (<a href="https://skillsmatter.com/skillscasts/11626-keynote-pushing-types-and-gazing-at-the-stars">link</a>):</p><ul><li>exploration of a problem (modelling a domain class for angles) and design of a solution in purely functional programming style</li><li>using Cats for various typeclasses (Semigroup, Monoid, Group, etc.)</li></ul><p>To be honest, the phrase “<em>types, Cats and Tagless Final</em>” could be improved a bit. “Types” is just too broad and “tagless final” is too specific (we’ve seen a fair share of its main rival, Free, as well some alternatives to both). Something like “<em>type-driven programming, interpreters and monad stacks in Cats</em>” would probably have been more precise. But I’m nitpicking; point is, whoever is even remotely interested in this particular subset of the vast Scala space, definitely (would have) had a great time at this year’s Scala eXchange.</p><p>Oh, and don’t forget that this is just one half of the whole theme; the other half is the data engineering Kafka/Spark side. Since there were four different talks to choose from in each given slot (apart from keynotes which were standalone), one could have taken such a path as well. Talk titles such as “Introduction to Kafka Streaming”, “Adaptive Recommender Systems with Apache Spark”, “Introduction to Functional Reactive Programming in Scala”, “Akka Cluster — Up and Running”, “Concurrency and Asynchrony in Scala” and “Validating Big Data Jobs — Stopping Failures before Production (w/ Spark, BEAM, &amp; friends!)” speak for themselves.</p><h3>Breaking the monotony</h3><p>Of course, not *everything* needs to fit under the announced thematic umbrella. For example, the Haskell talk listed earlier obviously has nothing to do with the declared topics (well, it does with the “types” part, but as I said that’s just too broad). However, talks like that are awesome at breaking the possible monotony and are usually very interesting in their own right.</p><p>Same goes for talks such as:</p><ul><li>“Program Description Based Programming“ by Luc Duponcheel (<a href="https://skillsmatter.com/skillscasts/12802-program-description-based-programming">link</a>)</li><li>“Formally Verifying Complex Systems Using TLA+” by Ruben Berenguel (<a href="https://skillsmatter.com/skillscasts/13265-lightning-talk-formally-verifying-complex-systems-using-tla">link</a>)</li><li>“Deep Learning: Programming with a Difference“ by Noel Welsh (<a href="https://skillsmatter.com/skillscasts/12818-deep-learning-programming-with-a-difference">link</a>)</li><li>“Reinforcement Learning in Scala” by Chris Birchall (<a href="https://skillsmatter.com/skillscasts/12821-reinforcement-learning-in-scala">link</a>)</li><li>“Fire and Fury” by Jon Pretty (<a href="https://skillsmatter.com/skillscasts/13122-fire-and-fury">link</a>)</li><li>etc.</li></ul><p>One of the biggest divergences, not only from the main theme, but from Scala in general, was the keynote by Dr Eugenia Cheng: Conveying the Power of Abstraction (<a href="https://skillsmatter.com/skillscasts/12089-keynote-conveying-the-power-of-abstraction">link</a>). A very refreshing talk by one of the best speakers at the whole conference, highly recommended.</p><p>Another thing that Scala eXchange did in order to keep things fresh is the so-called “fireside chat”, where Martin Odersky and Simon Peyton Jones, people who don’t need any introduction in the worlds of Scala and Haskell, sat side-by-side (hosted by Miles Sabin and Zainab Ali) and discussed various FP-related topics (<a href="https://skillsmatter.com/skillscasts/12961-fireside-chat-martin-odersky-and-simon-peyton-jones">link</a>). Being more casual in its tone than the talks themselves, it was cleverly placed as the first thing after lunch and served as a perfect introduction into the afternoon part of day 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQ7A4RWNPNmehVzkBCdcMg.jpeg" /><figcaption>Martin and Simon discussing Scala, Haskell, FP and common ski trips with Miles, Zainab and the audience</figcaption></figure><p>Last but not least, the so-called “lightning talks” also felt very appropriate. Being placed at the end of the first day’s schedule, they take into account the tiredness and information saturation which appears at that point, so they were each only 15 mins in length. Having three 15-mins talks works much better in those circumstances than a single demanding 45-mins talk, at least in my opinion.</p><h3>Conclusion</h3><p>As far as I’m concerned, Scala eXchange got the right balance. Even though there was still a colourful variety of different topics, a central theme was present, and I find that to be a very interesting approach. It put an accent on a particular subject, but it never allowed for things to get boring and for anyone to be forced to go, “Omg not another tagless-final talk” without being able to shake things up a bit.</p><p>Maybe I would be speaking differently if it were about something I didn’t find that interesting, e.g. project setup and dependency management with SBT. :) But this way, I really enjoyed it.</p><p>I already provided direct links for most of the talks I mentioned, but you can find all of them at <a href="https://skillsmatter.com/skillscasts">https://skillsmatter.com/skillscasts</a>.</p><p>Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34beb3fe01e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/skills-matter/scala-exchange-london-2018-a-topic-based-approach-to-conferences-34beb3fe01e2">Scala eXchange London 2018: A topic-based approach to conferences</a> was originally published in <a href="https://medium.com/skills-matter">Skills Matter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What's new in Scala 3]]></title>
            <link>https://medium.com/@sinisalouc/whats-new-in-scala-3-28d9c11eec30?source=rss-690955769210------2</link>
            <guid isPermaLink="false">https://medium.com/p/28d9c11eec30</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Sinisa Louc]]></dc:creator>
            <pubDate>Mon, 21 May 2018 16:53:42 GMT</pubDate>
            <atom:updated>2019-11-28T15:47:44.491Z</atom:updated>
            <content:encoded><![CDATA[<h3>What’s new in Scala 3</h3><p>Here’s a short digest for all those who are still unfamiliar with the changes and improvements that are coming in Dotty / Scala 3. I’m not presenting anything that’s not already been presented elsewhere; I’m merely taking a bunch of sources — Dotty documentation, conference talks, blogposts, Google groups, SIPs, pull requests, etc. — and combining them into a text that’s (hopefully) easy to read, not diving too deep into any of the upcoming changes, but still providing enough detail to get you all excited about them.</p><p>Update: Please keep in mind that this was written in May 2018., meaning that some information might be outdated.</p><h3>Intersections and unions</h3><p>Type system is going through some major face-lifting.</p><p>First of all, we’re getting true <strong>union</strong> and <strong>intersection</strong> types. Now you might be thinking “what’s the big deal, intersection types are nothing but <em>A with B</em>, and we modeled union types without problems with constructs such as Either or subtyping hierarchies (e.g. Apple and Banana extend Fruit)”. That is true, we had those mechanisms and we will still have them, but intersection and union types are slightly different.</p><p>Let’s start with union types. A union type, expressed as <em>A | B,</em> represent a “true” union, as opposed to a disjoint union (also known as tagged union) that we have with Either, scalaz disjunction etc. Disjoint union clearly separates between the “left” and “right” case, but standard non-disjoint union doesn’t. This means that there’s no Left and Right; you can literally do this:</p><pre><strong>val </strong>a: A | B = <strong>new </strong>A()<br><strong>val </strong>b: A | B = <strong>new </strong>B()</pre><p>They are commutative, so A | B is the same as B | A.</p><p>To be perfectly honest, there are probably not going to be extremely many places where you will actually want to use a union type instead of Either, Option etc., but that’s because the latter are monads which come equipped with handy functions such as map, flatMap, filter etc. But unions will definitely come handy in domain modeling, where we often resorted to aforementioned subtyping hierarchies. This will be super-handy if you had a slightly complicated case of intersections on middle levels of the hierarchy; fore example, let’s say we have traits Dog, Bird and Bat. Then there are traits CanSee (only extended by Dog and Bird), CanFly (only Bird and Bat) and Mammal (only Dog and Bat). Or we don’t want them to sound so general because those two types are all that will ever extend them, so we name them more specifically DogOrBird, DogOrBat, BirdOrBat. Super clumsy. With Scala 3 you’ll be able to simply state your type as Dog | Bird without those intermediate types in the hierarchy.</p><p>Intersection types (expressed as <em>A &amp; B</em>) represent a dual concept to union types, and just like with union types, there are already similar constructs present in Scala. We can already mix in traits B and C into some class/trait/object A, resulting in intersection type “A with B with C”. Main difference between such mixins and the intersection types we’re getting in Scala 3 is the commutativity: A with B is not the same as B with A, at least from the type system perspective, while A &amp; B and B &amp; A are the same thing and can be used interchangeably. Unlike disjoint unions and subclass hierarchies which still have advantages in certain use cases over Scala 3 unions, intersection types are basically commutative versions of standard mixins types. This means that “A with B with C” syntax will be deprecated in the future.</p><h3>Trait parameters</h3><p>As you know, traits cannot have parameters; we have abstract classes for that. However, abstract classes cannot be mixed into different parts of the class hierarchy.</p><p>Well, now the traits are getting parameters too, which means syntax like this:</p><pre><strong>trait </strong>Foo(<strong>val </strong>s: String) {<br>  ...<br>}</pre><p>This could lead us to the “diamond problem” in class hierarchies, e.g. both Foo(“a”) and Foo(“b”) have been mixed in at some point. That would actually not compile. Rules are as follows:</p><ul><li><strong>Only classes</strong> can pass arguments to their parent traits; traits cannot pass arguments to traits.</li><li>When a class C extends a parameterized trait T, it <strong>must</strong> provide the arguments to T, <strong>except</strong> if C has a superclass that also extends T; in that case, superclass must provide the arguments, and C cannot.</li></ul><p>This has been described quite nicely in the associated <a href="https://docs.scala-lang.org/sips/trait-parameters.html">SIP</a>. I’m pretty sure people will come up with various edge cases when using trait parameters, but let’s deal with those when the time comes. Birds-eye view of the feature looks pretty promising.</p><h3>Function types</h3><p>There are two main big things coming up regarding function types.</p><p>First, we are getting <em>dependent function types</em>. This means having types such as (a: A) =&gt; a.Foo. We already have dependent methods, but now we’re getting the possibility of turning such a method into a function, which is commonplace in Scala, but was impossible for methods whose return type was path dependent on the input type. Now we can do it:</p><pre><strong>def </strong>fooMethod(a: A): a.Foo = a.key<br><strong>val </strong>fooFunction: (a: A) =&gt; a.Foo = fooMethod</pre><p>Second most important function types feature, and I find this one personally very exciting, are <em>implicit function types</em>. There has been some confusion over this, so let me try to clear it up. Let’s take the following implicit function type:</p><pre><strong>type </strong>MyFunction[B] = <strong>implicit </strong>A =&gt; B</pre><p>This *does not* have the semantics of “implicit conversion from A to B”. Think of it like a “function of type A =&gt; B, where A is implicit”. Like in other scenarios with implicits, this means that if implicit value of type A is found in the scope, it will be passed; if no implicit A is in scope, it needs to be passed explicitly or the compilation will fail.</p><p>So given some method</p><pre><strong>def </strong>foo(f: Foo)(<strong>implicit </strong>a: A): B = ???</pre><p>we can rewrite that as:</p><pre><strong>type </strong>MyFunction = <strong>implicit </strong>A =&gt; B<br><strong>def </strong>foo(f: Foo): MyFunction</pre><p>This allows us to define foo as a *function value*. Without implicit function types, we can only define it as a method; right now in Scala 2, having implicit parameters in a method automatically means that it cannot be expressed as a function.</p><p>Implicit function types allow us some very handy refactoring. Unfortunately, I don’t have nearly enough space here to do full justice to implicit function types in terms of explaining their full usefulness. It would require a blogpost on its own, which I might even write one of these days. Several interesting use cases (e.g. removing boilerplate in the tagless final pattern, refactoring Dotty compiler context passing, some implementations of SQL queries etc.) have been presented in this <a href="https://slideslive.com/38908156/applications-of-implicit-function-types">very interesting talk</a> by Olivier Blanvillain at ScalaDays in Berlin, so if at the time of reading this a video of it is on YT, I really recommend you to watch it.</p><h3>Generic tuples</h3><p>This one is <a href="https://github.com/lampepfl/dotty/pull/2199">still open</a> at the time of writing this, but it’s happening for sure in Scala 3. Tuples are no longer going to be implemented via those awkward TupleN traits that (quite arbitrarily) end at Tuple22. Instead, they are going to be implemented similarly to how Lists are implemented, with their recursive-friendly <em>head :: tail </em>structure, which means that they are basically becoming shapeless HList.</p><p>Even though this means that the 22 limit is gone, that’s not the main advantage here (if you’re using a tuple with 22+ values, you should probably reconsider your domain design). Main improvement comes in the way we treat the tuples themselves, because nested tuples can now be treated as flattened;(a, b, c) will be exactly the same as(a, (b, (c, ()))). This allows for some nice generic programming similarly to what we can do with HLists, such as mapping over them with monomorphic or even polymorphic functions (the latter requires some shapeless trickery; check out these <a href="http://milessabin.com/blog/2012/04/27/shapeless-polymorphic-function-values-1/">excellent</a> <a href="https://milessabin.com/blog/2012/05/10/shapeless-polymorphic-function-values-2/">blogposts</a> by Miles Sabin).</p><h3>Opaque types</h3><p>Here’s a short explanation of a <em>newtype</em> for those who aren’t familiar with it: it’s similar to a type alias, but rather than being an alias just for the programmer, it’s also an alias for the compiler, meaning that the compiler actually differentiates the two. Let’s take the following type alias as an example:</p><pre><strong>type </strong>FirstName = String</pre><p>This gives us the possibility of using “FirstName” as a type, which can make the code more understandable. However, nothing prevents us from actually passing a “normal” String wherever FirstName is required. Even worse, if we have another type alias, e.g. LastName = String, nothing prevents us from accidentally passing a LastName where FirstName is expected and vice versa, since from the compiler’s point of view they are all just Strings.</p><p>If we want to achieve the behaviour where such usage would be prevented by the compiler, we need to resort to value classes. This means writing something like this:</p><pre><strong>class </strong>FirstName(<strong>val </strong>underlying: String) <strong>extends </strong>AnyVal<br><strong>class </strong>LastName(<strong>val </strong>underlying: String) <strong>extends </strong>AnyVal</pre><p>This is a bit boilerplate-y and has a slight performance hit due to boxing/unboxing. Adding the <em>extends AnyVal </em>part takes care of some of that performance penalty, but not in all use cases. Plus, our code looks awful!</p><p>There’s a <a href="https://github.com/estatico/scala-newtype">library</a> that allows defining them in a slightly more elegant way:</p><pre>@newtype <strong>case class </strong>FirstName(underlying: String)</pre><p>but this still feels like the same old boilerplate with some new syntax. Also, these newtypes must be defined in an object or package object.</p><p>Scala 3 is introducing <em>opaque types</em>.</p><pre><strong>opaque type </strong>FirstName = String</pre><p>People sometimes use the terms newtype and opaque type interchangeably. Others say that newtype is the one that wraps around the underlying type as we’ve seen earlier, while opaque types are defined “directly”. Others yet say that opaque types are a special kind of type alias that is created using a newtype. Don’t get confused by the terminology; concept is pretty much the same.</p><p>So yeah, opaque types give us exactly what we need. FirstName is a type on its own, and passing a value of type LastName where FirstName is expected won’t compile. There might be some resistance to introducing a new keyword, in which case the proposal is to use: <em>new type FirstName = String</em>. Either way, this will be a nice feature.</p><h3>Type lambdas</h3><p>We’re getting full language support for type lambdas without having to resort to ugly boilerplate or <a href="https://github.com/non/kind-projector">external libraries</a>.</p><p>Let’s take a popular use case where F[_] is needed, but we want to pass a type constructor that takes two types (such as Map or Either), or in other words, we want to pass (﹡ → ﹡) → ﹡where ﹡→ ﹡is needed.</p><p>Instead of having to define a type lambda like this:</p><pre>({ type T[A] = <strong>Map</strong>[Int, A] })#T</pre><p>we will be able to simply say</p><pre>[A] =&gt; Map[Int, A]</pre><p>Type parameters of lambdas will support variances and bounds, for example</p><pre>[+A, B &lt;: C] =&gt; Whatever[A, B, C]</pre><h3>Erased parameters</h3><p>There are situations where we only need some parameter(s) in the signature, e.g. for evidence in generalized type constraints, and they are never used in the body itself. Unnecessary code will still be generated for such parameters, which can be prevented by using the keyword “erased”.</p><p>For example,</p><pre><strong>def </strong>foo[S, T](s: S, t: T)(<strong>implicit</strong> ev: S =:= T)</pre><p>could and should be used as</p><pre><strong>def </strong>foo[S, T](s: S, t: T)(<strong>implicit</strong> <strong>erased</strong> ev: S =:= T)</pre><p>So whenever you have one or more parameters that are used only for type checking, using “erased” keyword will make your code more performant.</p><h3>Enums</h3><p>Yep, one of the clunkiest constructs in Scala gets a full redesign, which means replacing code like this:</p><pre><strong>object</strong> WeekDay <strong>extends</strong> Enumeration {<br>  <strong>type</strong> WeekDay = Value<br>  <strong>val</strong> Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value<br>}</pre><p>with code like this:</p><pre><strong>enum</strong> WeekDay {<br>  <strong>case</strong> Mon, Tue, Wed, Thu, Fri, Sat, Sun<br>}</pre><p>They can be parameterized and can contain custom members. They will also have some handy methods already pre-defined.</p><p>Example:</p><pre><strong>enum</strong> Weekday(<strong>val </strong>index: Int) { </pre><pre>  <strong>private def</strong> next(i: Int) = (i + 1) % 7<br>  <strong>private def</strong> prev(i: Int) = (i + 7) - 1 % 7</pre><pre>  <strong>def </strong>nextDay = Weekday.enumValue(next(index))<br>  <strong>def </strong>prevDay = Weekday.enumValue(prev(index))</pre><pre>  <strong>case </strong>Mon   <strong>extends </strong>Weekday(0)<br>  <strong>case </strong>Tue   <strong>extends </strong>Weekday(1)<br>  ...<br>}</pre><h3>Other</h3><p>Here are some additional features and improvements that I find important as well, but they don’t really require separate paragraphs to be explained.</p><p><strong>Multiversal equality:</strong></p><p>Compiler will now match the types when comparing values and fail the compilation if there’s a mismatch, e.g. “foo” == 123. We can already model this via type classes (it’s actually done in several libraries), but with Scala 3 we’re getting the native language support.</p><p><strong>Restricting implicit conversions:</strong></p><p>Compiler will now require a language feature import not only when an implicit conversion is defined but also when it is applied.</p><p><strong>Null safety:</strong></p><p>This is based on the union types feature, which allows us to define the result type of scary operations that can throw a null pointer exception (useful for interoperability with Java) as Foo | null.</p><p><strong>Extension clauses:</strong></p><p>These will basically be a replacement for implicit classes, e.g. <br>extension StringOps for String { … }, but I didn’t dig too deep into this yet. Take a look at <a href="https://github.com/lampepfl/dotty/pull/4114">this PR</a> if you want to find out more.</p><p><strong>Removing unneeded constructs:</strong></p><p>…such as early initializers, auto-tupling, existential types using forSome, automatic insertion of (), infix operators with multiple parameters, etc.</p><h3>Conclusion</h3><p>Scala 3 is going to be a big change, no doubt about that. I just hope that the upside of getting all these new exciting goodies will not be met with the downside of difficult switch from 2 to 3, which might result in a split community (such as when Python moved to the same major release). Tools are being developed in order to make the transitions and cross builds as painless as possible. One interesting thing that’s coming up is TASTY (Typed Abstract Syntax Trees; I guess “Y” is just making the acronym catchy). These trees contain all the information present in a Scala program, such as syntactic structure, info about types, positions etc. Once serialised into a TAST, it will be possible to port the Scala program to a different version, which will allow easy cross builds and solving the problems of binary (in)compatibility.</p><p>But let’s not ruin the moment talking about real-life problems :) as far as the language itself is concerned, Scala 3 is bringing a lot of improvements and interesting new features to the table, and I’m looking forward to it.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28d9c11eec30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Further demistifying the Monad in Scala: a Category Theory approach]]></title>
            <link>https://medium.com/free-code-camp/demistifying-the-monad-in-scala-part-2-a-category-theory-approach-2f0a6d370eff?source=rss-690955769210------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f0a6d370eff</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Sinisa Louc]]></dc:creator>
            <pubDate>Sat, 25 Feb 2017 18:14:51 GMT</pubDate>
            <atom:updated>2019-03-01T16:39:17.565Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OU9A2GD6x7ben-VtJogDIQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/D0MnQwrMvpg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lucien Kolly</a> on <a href="https://unsplash.com/search/photos/mist?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Some of you may have read my <a href="https://medium.com/@sinisalouc/demystifying-the-monad-in-scala-cc716bb6f534">article</a> on monads. This time I want to talk about monads from a different, more theoretical point of view. It is not mandatory to read the previous article first (in case you haven’t), but if you don’t know anything about the topic, I guess it wouldn’t hurt to become familiar with it before jumping on this one.</p><p>Let’s start. Some of you may have heard the popular quote:</p><blockquote>A monad is just a monoid in the category of endofunctors, what’s the problem?</blockquote><p>Original statement is from <em>Categories for the Working Mathematician</em> by Saunders Mac Lane, but it has been quoted and rephrased numerous times. I took this statement as a reference point; a teaching objective, if you will. So I will attempt to explain monads from the category theory point of view by explaining that particular sentence.</p><p>Important note: A lot of stuff written here is simplified and may not be 100% mathematically accurate. Category theory is a very complex field of mathematics (sometimes even jokingly referred to as “<a href="https://en.wikipedia.org/wiki/Abstract_nonsense">abstract nonsense</a>”). <br>This is not a math article. This is simply my attempt of creating an introductory, easy-to-follow text that should serve as a starting point to get you all excited about category theory and continue the exploration on your own.</p><h4>Algebraic structures</h4><p>What is a category? A category is an <em>algebraic structure</em>. OK, but what is an algebraic structure? Algebraic structure is basically a <strong>set</strong> (when used in this context of being an algebraic structure’s set, it is commonly referred to as <em>underlying</em> <em>set</em>) of one or more <strong>elements</strong> with one or more <strong>operations</strong> on them.</p><p>There are two main things that differentiate algebraic structures from one another:</p><ul><li>laws that need to hold for operations on set elements</li><li>existence of identity element</li></ul><p>Here are some laws that appear across different algebraic structures (operation in an algebraic structure is denoted as ○):</p><ul><li><em>Closure</em>: For all <em>a</em>, <em>b</em> in algebraic structure <em>M</em>, the result of operation <em>a</em> ○ <em>b</em> is also in <em>M</em></li><li><em>Invertibility</em>: For each element <em>a</em> in <em>M</em> there is an element <em>b</em> where <em>a</em> ○ <em>b</em> = <em>b</em> ○ <em>a</em> = <em>e</em> , where <em>e</em> is the identity</li><li><em>Commutativity</em>: for all <em>a, b</em> in <em>M</em>:<em> a ○ b = b ○ a</em></li><li><em>Associativity</em>: for all <em>a, b, c</em> in <em>M: (a ○ b) ○ c = a ○ (b ○ c)</em></li></ul><p>Identity element is an element which (quoting the <a href="https://en.wikipedia.org/wiki/Identity_element">wiki</a>) “leaves other elements unchanged when combined with them”. It’s the element that doesn’t affect the result when used in operation ○. We can formulate that into a law too:</p><ul><li><em>Identity</em>: for any <em>a</em> in <em>M </em>there is an element <em>e</em> where <em>e </em>○ <em>a = a </em>○ <em>e = a</em></li></ul><p>So, starting from a simple set with one or more operations and by adding a certain combination of the laws that are required, we can end up with various algebraic structures. Here are some:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-6_3HgUuITJhO11knQZrag.png" /></figure><h4>Category</h4><p>Category is an algebraic structure that consists of objects with defined mappings between some of them. Those mappings are called <em>morphisms </em>or <em>arrows</em>. Arrows go from one object to another. Some pairs of objects have an arrow between them defined, some don’t.</p><p>Categories have an important feature: if there is some arrow <em>f</em>: A → B and an arrow <em>g</em>: B → C, there is also automatically a <em>composition</em> of arrows <em>f</em> and <em>g</em> which forms an arrow A → C. We write the composition as <em>g ○ f</em>. Recall that algebraic structure is defined as a set with some operation(s) on its elements; in case of category, those elements are arrows and the operation is arrow composition.</p><p>Categories are completely abstract and this is quite tricky to wrap your mind around. “Give me an example of a category”, you ask. OK, here’s one — <em>Set</em>. <em>Set</em> is the <a href="https://en.wikipedia.org/wiki/Category_of_sets">category of sets</a>. Which sets? Does it include the set of integers, set of letters in english alphabet, set of all animals with four legs? Yes, it includes any and every set there is.</p><p>It’s not easy, but try not to think in completely concrete terms. Don’t try to materialise those sets. We don’t care how many sets are inside the category or which elements are inside those sets. We just care about the fact that objects in the Set category are sets and arrows are functions between sets that can be composed. I mean, that’s not all, there is a <a href="https://www.jstor.org/stable/72513">whole science</a> behind category of sets with lots of axioms and laws. But we have all we need for now.</p><p>Regarding our algebraic structure laws, category obeys two: <strong>identity </strong>and<strong> associativity</strong>. Since category is an algebraic structure with arrows as its elements and arrow composition as the operation between the elements, following those laws means that we have an identity arrow and that composition of arrows is associative.</p><p>Identity arrow is an arrow that goes from an object to itself. Composition of any arrow <em>f</em> with identity arrow <em>e</em> is arrow <em>f:</em></p><p><em>e ○ f</em> = <em>f</em> = <em>f</em> <em>○ e</em></p><p>Given arrows <em>f</em>, <em>g</em>, <em>h</em> and their composition <em>○</em>, the associativity law is:</p><p><em>h ○ (g ○ f) = (h ○ g) ○ f</em></p><p>Functions in your favourite programming language are another example of a category. Objects in this category are types and morphisms are functions that take a type and return a type. For any type there exists a function that returns that same type (identity) and functions compose easily, obeying associativity law. Note that functions of two or more arguments can be <a href="https://en.wikipedia.org/wiki/Currying">curried</a> and therefore viewed as functions of one argument that return a higher-order function.</p><p>That’s it for now regarding categories. Objects, arrows, composition, identity, associativity. Good. We’ll get back to them shortly.</p><h4>Monoid</h4><p>Getting warmer. What is a monoid?</p><p>Monoid can be defined as a:</p><p>- single set<em> S</em> <br>- with an associative binary operation <em>○</em><br>- and an identity element <em>e<br>- </em>following two laws:<br> <em>(a ○ b) ○ c = a ○ (b ○ c)<br> a ○ e = e ○ a = a</em></p><p>Note how similar this looks to a category. We will soon see what this means.</p><p>But first an example for a monoid. OK, so we need a set with an associative binary operation and with some identity element. We could take addition on the set of integers Z. Alright, we have an identity element (it’s zero) and we have the associativity, because (x + y) + z= x + (y + z). If you take another look at that table of laws for various algebraic structures, you’ll notice that addition in Z is in fact a group, because it also has an inverse (subtraction).</p><p>But here’s something cool and possibly a bit disturbing at the same time — monoid is actually a <strong>category</strong>, just a bit of a special one:<strong> it has only one object</strong>.</p><p>If you scroll back to the table we saw earlier you’ll see that monoid is actually pretty similar to a category, only difference being the closure law. Recall that closure says “for all <em>a</em>, <em>b</em> in algebraic structure <em>M</em>, the result of operation <em>a</em> ○ <em>b</em> is also in <em>M</em>”. It’s pretty logical we got the closure property in a monoid since we always start from and end up in the same object (the only one we have). Categories don’t have closure because not all arrows can necessarily be composed (e.g. you can’t compose <em>a → b</em> and <em>c → d</em>) so the property “combine any two elements and you’ll arrive at something that’s also a part of the set” doesn’t hold. Other two laws (identity and associativity) are the same.</p><p>When switching the viewpoint from <em>monoid as a set</em> to <em>monoid as a category</em>, elements of the set become arrows of the category, identity element becomes the identity arrow, and binary operation becomes arrow composition. And yes, as soon as we enter the twilight zone also known as category theory, stuff gets weird. But with a bit of mindset shifting, our addition-in-Z example can be seen as a category.</p><p>First of all, numbers are now arrows. Think of an arrow as an “add X” function. These functions compose quite nicely, since adding 3 to a number and adding 5 to the result is the same as adding 8 to the original number. Furthermore, composing add3 with add5 followed by composing with add7 is the same as composing add3 with the composition of add5 and add7:</p><p><em>(add3 ○ add5) ○ add7 = add3 ○ (add5 ○ add7)</em></p><p>To cite a particular <a href="http://bartoszmilewski.com/2014/12/05/categories-great-and-small/">great source</a> on category theory from which I took the adders example:</p><blockquote>Instead of giving you the traditional rules of addition, I could as well give you the rules of composing adders, without any loss of information.</blockquote><p>So, by shifting our viewpoint a little, we were able to see the monoid both as a set (on the left) and a single-object category (on the right).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*uV4Eca5vr02Ey57HSqT9eA.png" /><figcaption>(I took the photo from <a href="https://en.wikiversity.org/wiki/Introduction_to_Category_Theory/Monoids#From_Binary_Operators_to_Arrows">here</a>)</figcaption></figure><p>Also, all the laws that we had in the first case are also present in the second case. Nothing more, nothing less.</p><p>OK, so we no longer have numbers; we have add-arrows which represent single-parameter adding functions. Second operand of adding operation is “hardcoded” (operation is now unary, not binary) so we have one function for each natural number. Total count of natural numbers and total count of arrows in our category are the same. Finally, arrows all share the same starting and ending object.</p><p>This object is completely irrelevant; think of it as a massless blob of nothingness. If you want, we could rename arrows from “addX’ to simply “x” and then the whole thing becomes really similar to our normal good old set Z with addition, just instead of “adding two and two equals four” we would say “composing two and two equals four”.</p><p>Here are the wikis for both viewpoints, perhaps you’ll find them useful:</p><ul><li><a href="https://en.wikipedia.org/wiki/Monoid">monoid as a set</a></li><li><a href="https://en.wikipedia.org/wiki/Monoid_(category_theory)">monoid as a category</a>.</li></ul><h4>Functor</h4><p>Alright, now we know what algebraic structures are and how they are defined, and we also took a closer look into two of them — category and monoid. We saw that monoid is a category too, just with only one object.</p><p>What we need now is a <em>functor </em>(by the way, I already <a href="https://hackernoon.com/functors-and-applicatives-b9af535b1440#.zabfpezi1">wrote a bit about functors</a> too).</p><p>Compared to monoids and categories, functor is a bit different. It is not really an algebraic structure; it’s more of a function that <em>maps</em> from algebraic structures to algebraic structures. But not just any algebraic structures: functor is a <strong>mapping between categories.</strong></p><p>Category, as we know by now, is a set of objects with arrows between them. Well, functor knows how to map the category to another category. It will map all the objects and all the arrows, and it will preserve the connections between objects (if there is an arrow between <em>a</em> and <em>b</em> in original category, there will be one between <em>Fa</em> and <em>Fb</em> in the resulting category). Given some object <em>a</em> or some arrow <em>f: a → b</em> from the original category, corresponding object (the one functor maps into) is denoted as<em> F(a)</em> and corresponding arrow is denoted as <em>F(f): F(a) → F(b)</em>.</p><p>Functor that maps a category back to that same category is called an <em>endofunctor. </em>Quick detour from the category theory into the real world — in programming, we deal with functors in category of types, and they are all endofunctors. They map a category of types back to category of types. Whenever you mapped something (<em>map</em> in Scala, <em>fmap</em> in Haskell) you had an endofunctor in your hands. For example, Option, List and Future are all valid endofunctors. Basically anything that has a map() function is an endofunctor.</p><p>Don’t take this for granted though; it’s merely a convention. Some library may provide you with an object whose map() doesn’t obey the functor laws (see the <a href="https://hackernoon.com/functors-and-applicatives-b9af535b1440#.zabfpezi1">old article</a>) which would mean that the object itself cannot be considered a functor.</p><p>Example: in Scala we can map from List[Int] to List[String] (in other words, to map all elements of a List from Int to String):</p><pre>List(1, 2, 3).map((x: Int) =&gt; x.toString)</pre><p>We can have all kinds of mappings: from Int to String, from String to List[String], from List[String] to Banana etc. All of them are Scala types. This means we always map from a category of Scala types back to the category of Scala types. Hence the “endo” part.</p><p>Now let’s “rip out” the map() method from some functor F and view it as a function of two arguments — a functor object and a function which we map it with. For example, List(1, 2, 3).map(f) becomes map(f, List(1, 2, 3)).</p><p>If we curry that, it’s easy to see that signature of <em>map</em> is:</p><p><em>(a → b) → F[a] → F[b]</em></p><p>Function which we map with is denoted as <em>a → b</em>, starting functor object is <em>F[a] </em>and result functor is<em> F[b].</em> Note that instead of providing both arguments, function <em>a → b </em>(e.g. <em>(x: Int) =&gt; _.toString()</em>) and a functor instance <em>F[a] </em>(e.g. <em>List(1, 2, 3)</em>), we can provide only the function <em>f,</em> in which case we get back a function <em>F[a] → F[b]</em> (if this is not something you’re comfortable with, do a quick research on currying and partially applied functions)<em>.</em> So yeah, instead of providing both arguments of type A and B and getting back a value of type C, we can provide only parameter of type A and get back a function B <em>→</em> C. Providing only number 4 to a function which sums two numbers gives us back a function that takes some number <em>n </em>and returns <em>n+4</em>.</p><p>Let’s take another look at this interesting function <em>(a → b) → F[a] → F[b]</em>. It’s a function from <em>(a → b) </em>to <em>F[a] → F[b].</em> To put it in category theory terms — it maps a category to another category, where objects of destination category carry the F symbol. Remember what we said earlier? “Given some object <em>a</em> or some arrow <em>a → b</em> from the original category, corresponding object (the one functor maps into) is denoted as<em> F(a)</em> and corresponding arrow is denoted as <em>F(a) → F(b)</em>.” That’s exactly what map does.</p><p>But we are missing something. We saw just one half of being a functor: the one that maps morphisms. A <strong>function on functions</strong>. It takes a function and returns the “lifted” version of that function, that is, one that instead of taking <em>a</em> and returning <em>b</em> now takes <em>F[a]</em> and returns <em>F[b]</em>. By the way, in practice we often don’t just lift functions and save them for later. Instead we immediately apply them to a functor instance. For example, instead of lifting a function <em>Int → String</em> to <em>List[Int] → List[String]</em>, we usually pass in an instance of <em>List[Int]</em> right away (or, in case of Scala, we invoke map() as a method on an instance of <em>List[Int]</em>)).</p><p>However, we know that functor not only maps all source arrows to destination arrows, but also maps all source objects to destination objects, right? But we only saw the mapping of arrows, when we lifted <em>a → b </em>to<em> F(a) → F(b)</em>. How to map <em>a</em> itself (and <em>b</em>, for that matter)? This is another side of a functor: apart from the function on functions, there is also a (somewhat implicit) <strong>function on types</strong>. Functor’s mapping of arrows is represented by the function-on-functions part, while mapping of objects is represented by the function-on-types part.</p><p>What is this function on types? It’s a <em>unary type constructor</em>. This means that, given some type, functor produces another new type. So if we take List functor as an example, given a String it gives us a List[String]. Given some type A, it gives us a List[A]. Type constructor for functors can be described in a more general way as * → * (takes one type as a parameter and produces a new type from it). <a href="http://blogs.atlassian.com/2013/09/scala-types-of-a-higher-kind/">Here’s</a> some more useful reading on type constructors.</p><p>Quick wrap-up of functors. Each functor is a mapping of categories. It maps some source category C to destination category F by mapping objects in C to objects in F and morphisms in C to morphisms in F. We say that (quoting myself) “given some object <em>a</em> or some arrow <em>f: a → b</em> from the original category, corresponding object (the one functor maps into) is denoted as<em> F(a)</em> and corresponding arrow is denoted as <em>F(f): F(a) → F(b)</em>”.</p><p>As (Scala?) programmers, we are working with the category of types in Scala (category of types in Haskell is called <em>Hask</em>, so I guess the Scala one could be called <em>Sca</em> or something). Here objects are Scala<em> </em>types and morphisms are functions between those types. Each functor in <em>Sca</em> maps the objects (Scala types) via the <em>type constructor</em>, and morphisms (functions on Scala types) via function <em>map</em>. If we take Option as an example, it maps every object in <em>Sca </em>(that is, every Scala type) into Option(thatObject), and every morphism between objects in Scala (that is, function between Scala types) into Option(thatFunction).</p><p>And since it’s a functor <em>Sca → Sca</em>, it’s more specifically an <em>endofunctor</em>.</p><h4>Monad</h4><p>Now that we know what category, monoid and endofunctor are, we can imagine a category of endofunctors and try to find a monoid in that category. As the famous statement by mr. Mac Lane tells us, monoid in the category of endofunctors is in fact a monad.</p><p>What does it mean to be a monoid in some category? For example, a monoid in the category Set (remember, that’s the category of all sets). What is it? Well, take a look at the category; it contains all imaginable sets. Now pick out those that satisfy monoid laws, that is, pick out all those sets for whose elements we can find an <em>identity element</em> and define an <em>associative binary operation</em>.</p><p>One such set is the set of integers with identity element being zero and binary operation being addition. Note that monoidal binary operation on set S must operate on two operands, both from S, and return something that is also an element of S.</p><p>Cool, so a monoid in the category Set is any set that has those properties, that is, those two operations (for example, the set of natural numbers with addition). <a href="https://en.wikipedia.org/wiki/Monoid_%28category_theory%29#Examples">Here</a> are some more examples of monoids in the category of X.</p><p>Let’s now see about “monoid in the category of endofunctors”. In this category, <strong>objects are endofunctors</strong> and <strong>arrows are mappings between those functors</strong>. An extra bit of terminology before we continue: mappings between functors are called <a href="https://en.wikipedia.org/wiki/Natural_transformation">natural transformations</a>. They operate on a yet higher level of abstraction:</p><ul><li><em>arrows</em> map objects within a category from one to another</li><li><em>functors</em> map categories from one to another</li><li><em>natural transformations</em> map functors from one to another</li></ul><p>We could also say that a natural transformation is an “arrow between functors”, and that’s exactly what we have here — we have a category of endofunctors, which means that objects are endofunctors themselves, and arrows between those endofunctors are by definition natural transformations.</p><p>Back to our search for monads. So what we are doing is reaching into the category of endofunctors and looking for such objects of that category for which two particular arrows are defined — identity and associative binary operation. When we have those two arrows, we have a monoid (in the category of endofunctors).</p><p>So we need an endofunctor F for which the following operations are defined:</p><ul><li><em>η</em>: <em>I → F</em></li><li><em>μ</em>: <em>F x F → F</em></li></ul><p>where I is the identity endofunctor, <em>η</em> (eta) is the fancy math name for <em>identity</em> on endofunctors, and <em>μ</em> (mu) is the fancy math name for <em>associative binary operation </em>on endofunctors. If you’re unsure where these two came from all of a sudden, remember that when we talked about monoid as a set, I showed you a <a href="https://en.wikipedia.org/wiki/Monoid_%28category_theory%29">wiki link</a> which, as you can see, uses those exact two operations (more precisely, arrows in the monoidal category) to define a monoid (in the monoidal category).</p><p>Let’s examine those two operations in the context of category of endofunctors and see what they become in that case:</p><ul><li><em>Identity</em> is a natural transformation mapping from an identity endofunctor (a functor which maps a category to itself) to another endofunctor.</li><li><em>Asssociative binary operation</em> is some operation x that knows how to take two endofunctors and turn them into one. Keep in mind that this operation must be associative, so (F x F) x F must yield the same result as F x (F x F).</li></ul><p>Now let’s see how each of these two operations materialize in the Scala world.</p><p>First, <em>η</em>: <em>I → F.</em> What identity functor <em>I </em>does is it maps any category back to itself. That means its “type constructor” doesn’t actually create any new type<em> F(value)</em>. It just leaves the value as it is. So what nat. transformation <em>η </em>really<em> </em>does is — it takes an identity functor and wraps it into a functor <em>F</em> context. In category of Scala types, identity functor maps a type back to itself, so we can view this whole transformation as lifting a Scala type into some F context, where F can be any functor.</p><p>What about <em>μ</em>:<em> F x F → F</em>? It’s a composition of two identical functors which results in just one. It’s a way to turn F[F[T]] into F[T].</p><p>Based on what we just said, it’s pretty logical to have <strong><em>apply</em></strong> as <em>η </em>and <strong><em>flatten</em></strong> as <em>μ. </em>Method<em> apply</em> constructs a type F[x] from x , while <em>flatten</em> “flattens” the composition F[F[x]] into F[x].</p><p>So whenever you see an endofunctor in Scala (in practice this is almost any object with method <em>map</em>, but remember to check the functor laws before you declare something a functor; for example, there’s a way to break those laws for Set) that also has <em>flatten </em>and<em> unit</em>, you are in fact dealing with a monad.</p><h4>Three monad definitions and monad laws</h4><p>We saw that monad is an endofunctor (remember, any functor in a programming language is actually an endofunctor because it maps from the category of types back to category of types) with two natural transformations:</p><ul><li>identity/unit implemented as <em>apply,</em> and</li><li>associative binary operation implemented as <em>flatten</em> (note that terms <em>unit</em> and <em>identity</em> are used interchangeably; I tend to use unit when talking from a practical, programming viewpoint, and identity when talking about category theory, but sometimes I may mix them up; they’re the same thing).</li></ul><p>Also, since we are talking about an (endo)functor, we know that there is a <em>map</em> method available too.</p><p>You may have heard about monad consisting of <em>unit</em> and <em>flatMap</em>. Yep, that’s correct; we can simply “squash” the <em>flatten</em> (coming from <em>μ</em>)<em> </em>and <em>map</em> (coming from its functor nature) methods into a single <em>flatMap</em> method. Our monad would still retain the same properties, it’s just that its associative binary operation would no longer be <em>flatten</em>, but <em>flatMap</em>. Monad laws (explained later) are not harmed.</p><p>So there are two valid definitions of a monad? One that involves <em>unit</em> and <em>flatMap</em> and one that involves <em>unit</em>, <em>flatten</em> and <em>map?</em></p><p>Yes. And not just that — there’s also a third one. <strong>Monads can be expressed in three different ways. </strong>All three definitions are equivalent and we can easily transform one into another. Here they are:</p><ul><li>unit + flatMap</li><li>unit + flatten + map</li><li>unit + compose</li></ul><p>All three are equally powerful and each one can be expressed by using one of the other two. We’ll talk more about them later.</p><p>Now, every monad implementation (e.g. List, Option etc.) needs to obey the <strong>monad laws</strong>. Monad laws can be expressed in three different ways, depending on which monad definition you are using, but they all resemble the same core concept.</p><p>Here are the monad laws presented using the <em>unit + flatMap </em>definition:</p><ul><li><strong>left-identity law</strong>: <br><em>unit(x).flatMap(f) == f(x)</em></li><li><strong>right-identity law</strong>: <br><em>m.flatMap(unit) == m</em></li><li><strong>associativity law</strong>:<br><em>m.flatMap(f).flatMap(g) == m.flatMap(x ⇒ f(x).flatMap(g))</em></li></ul><p>It is obvious that <em>unit + flatMap </em>definition is easily transformed to <em>unit + flatten + map </em>and vice versa because <em>flatMap = flatten + map. </em>I will now show the connection between <em>unit</em> + <em>flatMap</em> and <em>unit</em> + <em>compose</em>. I like the <em>unit + compose </em>definition because it makes the laws easier to express.</p><p>Let’s see the <em>compose</em> function:</p><pre>def compose: (A =&gt; F[B]) =&gt; (B =&gt; F[C]) =&gt; A =&gt; F[C]</pre><p>This is a two-parameter function where both parameters are functions of type<em> A → F[B]</em>, and the result is also a function of the same type. Note that types A and B are completely free and may represent any concrete types in Scala (<em>A→F[B]</em> could be e.g. <em>Int → List[String]</em> or<em> Int → Set[Int]</em>). We use the letters simply to denote that the parameter of the first function is the same type as the parameter of the result function (here denoted as “A”).</p><p>By the way, functions of type A <em>→ </em>F[B] are called <em>Kleisli arrows</em>, just in case you stumble upon the term somewhere. We say that the function we just defined has Kleisli arrows as parameters and also as return type. It’s a <em>composition of Kleisli arrows</em>.</p><p>Now let’s also define “unit”:</p><pre>def unit: A =&gt; F[A]</pre><p>We can easily check that this is indeed unit: it’s a neutral element that, when composed with, gives back the original element. Just take the signature and replace F[C] with F[B] so that the second parameter becomes an identity function:</p><pre>(A =&gt; F[B]) =&gt; (<strong>B =&gt; F[B]</strong>) =&gt; A =&gt; F[B]</pre><p>Again, types A, B and C are not fixed and can represent any concrete type so <em>A → F[A]</em> from the first identity expression is the same function as <em>B → F[B] </em>in this expression. You can think of identity function not as A <em>→ </em>F[A], but as Whatever <em>→ </em>F[Whatever] if you wish:</p><pre>(A =&gt; F[Whatever]) =&gt; (Whatever =&gt; F[Whatever]) =&gt; A =&gt; F[Whatever]</pre><p>So if we apply identity function as a second operand to <em>compose,</em> we will arrive back at our first operand. Good, composing identity with some function results in the same function. Identity holds. Associativity is pretty clear too; I will leave it to you to try and prove it by yourself.</p><p>What I wanted to show you is that <em>compose</em> can be expressed by using <em>flatMap</em>. Same goes in the other direction too; <em>flatMap</em> can be expressed by using <em>compose</em>.</p><p>Here it is:</p><pre>trait Monad[F[_]] {</pre><pre>  def flatMap[A, B](fa: F[A], f: A =&gt; F[B]): F[B] = ???</pre><pre><em>  </em>def compose[A, B, C](f1: A =&gt; F[B], f2: B =&gt; F[C]): A =&gt; F[C] = {<br>    a =&gt; flatMap[B, C](f1(a), f2)<br>  }<br>}</pre><p>And the other direction:</p><pre>trait Monad[F[_]] {<br><br>  def compose[A, B, C](f1: A =&gt; F[B], f2: B =&gt; F[C]): A =&gt; F[C] = ???<em><br><br>  </em>def flatMap[A, B](fa: F[A], f: A =&gt; F[B]): F[B] = {<br>    compose[Unit, A, B]((u: Unit) =&gt; fa, f)()<br>  }<br>}</pre><p>As I said earlier, <em>unit</em> + <em>compose</em> is particularly great for one specific purpose, and that is expressing monad laws. They become simpler to read and understand. Here they are again, this time using <em>compose</em> instead of <em>flatMap</em>:</p><ul><li><strong>left-identity law</strong>: <br><em>unit.compose(f) == f</em></li><li><strong>right-identity law</strong>: <br><em>f.compose(unit) == f</em></li><li><strong>associativity law</strong>:<br><em>f.compose(g.compose(h)) == (f.compose(g)).compose(h)</em></li></ul><p>Remember that all three definitions are equally “good”, that is, all three are minimal sets of operations needed to define a monad and each one can be expressed by using one of the other two.</p><p>Always remember that monad laws are the essence of what makes monads what they are. Having monad operations (e.g. <em>unit</em> + <em>flatMap</em>) is not enough if the laws are not satisfied.</p><h4>Summary</h4><p>Our initial objective is complete. We now understand that famous sentence. <strong>Monoid in the category of endofunctors is any endofunctor with operations <em>η </em>and<em> μ</em>, and we call such endofunctor a <em>monad</em></strong> (reminder: objects of that category are endofunctors and arrows are natural transformations).</p><p>So, monad can be defined in many ways, such as:</p><ul><li>monoid in the category of endofunctors</li><li>object in the category of endofunctors with arrows <em>η </em>and <em>μ</em></li><li>endofunctor with natural transformations <em>η </em>and <em>μ</em></li></ul><p>In Scala, <em>η </em>is implemented as <em>apply</em> and <em>μ</em> is implemented as <em>flatten</em>, which means that monad is any functor (that is, a construct with <em>map</em> method) that is additionally equipped with <em>apply</em> and <em>flatten</em>. There are two more completely equally valid ways of defining a monad in terms of its operations: <em>unit</em> + <em>flatMap</em> and <em>unit</em> + <em>compose</em>. They are completely equal and there is nothing one can do that others can’t. We saw how <em>flatMap</em> can be expressed using <em>compose</em> and vice versa; this is possible for all combinations.</p><p>And don’t forget about the monad laws.</p><h4>Final word</h4><p>Hopefully this article helped you gain some perception as to how certain category theory constructs fit together and, more specifically, what our old friends monads “really are” — monoids in the category of endofunctors.</p><p>By the way, the name monad comes from “monoid” and “triad”; monoid because it’s a monoid in the category of endofunctors, and triad because it’s a package of three things: an endofunctor equipped with two natural transformations.</p><p>That’s all for now. As usual, if you find any mistakes please do let me know via email (sinisalouc[at]gmail[dot]com). You can also find me on <a href="http://twitter.com/sinisalouc">Twitter</a>.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f0a6d370eff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/demistifying-the-monad-in-scala-part-2-a-category-theory-approach-2f0a6d370eff">Further demistifying the Monad in Scala: a Category Theory approach</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generalized type constraints]]></title>
            <link>https://medium.com/hackernoon/generalized-type-constraints-b256e79dd266?source=rss-690955769210------2</link>
            <guid isPermaLink="false">https://medium.com/p/b256e79dd266</guid>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Sinisa Louc]]></dc:creator>
            <pubDate>Sat, 20 Aug 2016 13:32:47 GMT</pubDate>
            <atom:updated>2017-07-13T22:19:50.924Z</atom:updated>
            <content:encoded><![CDATA[<p>In this short article I will demonstrate the generalized type constraints in Scala — what they are, why we need them and how they are used.</p><p>To start, let me show you two Scala puzzles.</p><h4>Puzzle number one:</h4><pre>def pair[S](s1: S, s2: S): (S, S) = (s1, s2)</pre><p>What do you think happens if we pass two values of different type to this method? Let’s see:</p><pre>scala&gt; pair(“foo”, 1)<br>res0: (Any, Any) = (foo,1)</pre><p>What happened is that compiler said “OK, first value is a String and second value is an Int, but that’s not really going to work out because I need those two arguments to be of the same type. I will now try to find their nearest common supertype. Here it is — it’s Any. Cool, each of these arguments is also an Any, so I will consider them to be of type Any in order to satisfy the type constraint”.</p><p>By the way, if we had a bound on type S, for example:</p><pre>def pairVals[S &lt;: AnyVal](s1: S, s2: S) = (s1, s2)</pre><p>Then invoking the method with String and Int would give us a compile error, because one of the arguments is not a subtype of AnyVal (remember that String is a subtype of AnyRef, not AnyVal). Compiler says “nearest common supertype of the arguments you gave me is Any, but that violates the given type constraint”:</p><pre>scala&gt; pairVals(“foo”, 4)<br>&lt;console&gt;:12: error: inferred type arguments [Any] do not conform to method pairVals’s type parameter bounds [S &lt;: AnyVal]</pre><p>Back to pair() method. Here’s a question — what if we wanted to say “method pair() should take two arguments of the <strong>same type</strong>”? We saw that pair() easily allows us to pass in a String and an Int; compiler will simply deduce that you passed values of type Any. What if we want to allow only invocations where both arguments share the exact same type (e.g. two Ints or two Strings, but not one Int and one String)?</p><p>Before I answer that, here’s another puzzle:</p><h4>Puzzle number two:</h4><pre>def advPair[S &lt;: T, T](s: S, t: T): (S, T) = (s, t)</pre><p>This is the same principle in a bit different situation. What do you think happens when we invoke this method with two different arguments?</p><pre>scala&gt; advPair(“foo”, 1)<br>res0: (String, Any) = (foo,1)</pre><p>You might at first glance conclude that advPair() takes two arguments, first being the subtype of second, and for that reason invoking it with String and Int will fail (because String is not a subtype of Int). Again, you would be wrong. Just like in the first case, compiler will try to work out the mess and see if it can satisfy the type constraints by upcasting your values. <em>(BTW don’t mind me using the term “upcasting” — I know it sounds a bit ugly, but you and I both know that there’s nothing ugly going on. Int *is* an Any, just like everything else in Scala).</em></p><p>So yes, we passed in a String and an Int, but Int is also an Any. When we look at things from that perspective, everything works out — we passed a String and an Any and the condition of first argument being a subtype of second is fulfilled.</p><p>So how can we put constraints on “original” types, without the compiler trying to be generous and upcasting our arguments until the type constraints are satisfied?</p><h4>Answer(s):</h4><p>By using <em>generalized type constraints</em>.</p><p>First puzzle solved:</p><pre>def pair[S, T](s: S, t: T)<strong>(implicit ev: S =:= T)</strong>: (S, T) = (s, t)</pre><p>Second puzzle solved:</p><pre>def advPair[S, T](s: S, t: T)<strong>(implicit ev: S &lt;:&lt; T)</strong>:(S, T) = (s, t)</pre><p>See those implicit parameters? They are the solution to our predicament. You can look at them as types: statement S =:= T is of same nature as, for example, Map[S, T]. It’s just that generalized type constraint (“GTC”) is infixed instead of prefixed.</p><p>So what happens when you have a GTC? Well, compiler will do its inferring magic as if the GTC weren’t there. <strong>Once everything is resolved, it will check if GTC is satisfied.</strong> See how in the pair() example we no longer have two arguments of type S, but arguments of different types, and return type is also changed from (S, S) to (S, T)? This way compiler will not need to do any upcasting magic — it will simply pair up the given arguments into a tuple. However, before proceeding with the method body, it will check if the GTC is satisfied; that is, whether types S and T are, in fact, the same type.</p><pre>scala&gt; pair(“foo”, 1)<br>&lt;console&gt;:12: error: Cannot prove that String =:= Int.<br> pair(“w”, 1)<br> ^</pre><pre>scala&gt; pair(“foo”, “foo”)<br>res0: (String, String) = (w,a)</pre><p>Second method also went through some changes in the type constraints — we removed the [S &lt;: T] part. Why? Again, to prevent the compiler from doing any upcasting magic. We saw how having [S &lt;: T] caused the compiler to upcast the Int into Any in order to conform to the type constraint, right? Well, now compiler will happily realize that there are no type constraints, which means that S and T can be String and Int without any problems, so it will proclaim its final decision: S is String, T is Int. But then GTC kicks in and tells the compiler “OK, now that you’ve resolved S and T to concrete types, here are my demands”. And if S is not a subtype of T, invocation will fail.</p><pre>scala&gt; advPair(“foo”, 1)<br>&lt;console&gt;:12: error: Cannot prove that String &lt;:&lt; Int.<br> advPair(“foo”, 1)<br> ^</pre><pre>scala&gt; val any: Any = &quot;any&quot;<br>any: Any = any</pre><pre>scala&gt; advPair(&quot;foo&quot;, any)<br>res0: (String, Any) = (foo,any)</pre><h4>Conclusion</h4><p>So here’s the summary:</p><p>Compiler will try to conform to type bounds by upcasting the types as needed, trying desperately to find a combination that works. If the process fails, compiler will cry. If it succeeds, compiler will assign each generic type parameter a concrete type (e.g. S and T will become String and Int).</p><p>Then, when the types are resolved, compiler will see that an implicit GTC is needed and it will provide it. Note that when you are writing a method that needs the GTC, you just need to declare it as an implicit parameter and that’s it. Compiler will provide the needed GTC at compile time and plug in the resolved types, issuing an error message in case GTC is not satisfied.</p><p>Fun with types never ends in Scala. :) As usual, contact me on sinisalouc@gmail.com with feedback or <a href="https://twitter.com/sinisalouc">find me on Twitter.</a></p><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a>family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp;sponsorship</a> opportunities.</blockquote><blockquote>To learn more, <a href="https://goo.gl/4ofytp">read our about page</a>, <a href="http://bit.ly/HackernoonFB">like/message us on Facebook</a>, or simply, <a href="https://goo.gl/k7XYbx">tweet/DM @HackerNoon.</a></blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b256e79dd266" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/generalized-type-constraints-b256e79dd266">Generalized type constraints</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functors and Applicatives]]></title>
            <link>https://medium.com/hackernoon/functors-and-applicatives-b9af535b1440?source=rss-690955769210------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9af535b1440</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Sinisa Louc]]></dc:creator>
            <pubDate>Thu, 07 Jul 2016 20:09:05 GMT</pubDate>
            <atom:updated>2018-10-23T20:59:59.456Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@sinisalouc/demystifying-the-monad-in-scala-cc716bb6f534#.1rcp1f12c">one of my earlier articles</a> I tried to explain monads in an approachable way. Here’s an attempt to do the same for some other members of the same family — functors and applicative functors. Even though concepts and principles explained here are general in functional programming, mild accent will be (as usual) on Scala.</p><h4>Functors</h4><p>In case you read the aforementioned article about monads, you may remember how I described them as wrappers around values. Every value wrapped in a monad becomes an object equipped with two methods, <em>unit</em> and <em>flatMap</em> (using Scala convention for naming).</p><p>So, if you look at a monad as a wrapper (I also like the word “context”) which provides those two methods, then you can look at a <em>functor</em> simply as another kind of wrapper; one that provides a slightly weaker version of a monad.</p><p>All you get is:</p><ul><li><strong>map</strong> (<em>fmap</em> in Haskel; like monad’s flatMap, but without the flatten part)</li></ul><p>Function <em>map</em> probably at least sounds familiar, although I’m quite sure most of you have used it in practice. Beginners are usually introduced to it using the list/array/someOtherCollection example, but the thing is that <em>all functors</em> have this function. You can map every element inside a List or a Set, but you can also map the value inside a Future or an Option into another value (of same or different type).</p><p>Moving on, but first we have to sort something out. Didn’t I declare Future, Option, List etc. to be <em>monads</em> in the monad article? Yes, I did. Everything that’s a monad is also a functor; you can look at it from the OOP perspective as monad being a subclass (or a subtype) of functor. OK, don’t really go around saying this to everyone because if you stumble upon category theory mathematicians, they could start talking about functors being simply mappings of elements and morphisms between categories while monads are actually monoids in the category of endofunctors with natural transformations being defined as functor composition and identity functor. I’m not kidding; they actually talk like that. But yes, from a programmer’s point of view it is completely valid to say that monad is in fact a functor, with extra stuff on the side. More specifically, on top of functor’s <em>map</em> monad has a <em>flatten</em> (also known as <em>join</em>), which enables it to define an upgraded version of map — our beloved <em>flatMap </em>(also known as <em>bind</em>)<em>.</em> Remember that monad also has a less interesting, but not less important, <em>unit</em> method.</p><p>Remember monad laws? We have some laws here too. Given that <em>m</em> is our functor instance (e.g. List or Future) holding some value (e.g. Int) and functions <em>f</em> and <em>g</em> are single-parameter functions that transform that value (in our example they must have signature Int → Something), then we can define the two functor laws as follows:</p><ul><li><strong>identity law</strong>: <br><em>map id = id<br></em>or Scala-way: <em>m.map(identity) == m</em></li><li><strong>distributive law</strong>: <br><em>F map f map g = F map (g ◦ f)</em><br>or Scala-way: <em>m.map(f).map(g) == m.map(x =&gt; g(f(x))</em></li></ul><p>Here <em>identity</em> is the identity function defined in predef package in Scala (given a value, it simply returns that same value) and <em>◦</em> is the standard mathematical notation for function composition (meaning “g after f”, or “apply f and then g”). Note that you can use <em>compose</em> or <em>andThen</em> if you want to compose two functions in Scala; however, that’s not the point of this article so I went for the easiest form and simply apply them one after another: <em>g(f(x))</em>.</p><h4>Heavy lifting</h4><p>Instead of map() taking two parameters, we will now curry it. This means that function e.g. <em>(Int, Int) → Int</em> will now become <em>Int → Int → Int</em>. Remember that this is right-associative, so it’s the same as <em>Int → (Int → Int)</em>. If you’re not familiar with currying, we’ll get back to it shortly.</p><p>Let’s take a List as a functor; our starting point (that is, our starting functor instance) can be, for example, List(1, 2, 3). Let’s also take some function that we can map our List with, such as:</p><pre>val f = (x: Int) =&gt; x.toString</pre><p>In Scala we would map this list as simple as <em>List(1, 2, 3).map(f)</em>. Now, if we shift our viewpoint as we did before so that map becomes a binary function, we could invoke it as <em>map(List(1, 2, 3), f)</em>. First argument is the functor instance and second argument is the function. <em>(Note that I’m making up syntax here; I’m merely illustrating a concept. In all standard Scala constructs map() will always be a class method that is invoked upon an instance of that class and it will take only one argument — the mapping function. It’s the convention.)</em></p><p>We said we would take it one step further and curry it, so invocation of our map function now becomes this (note that I switched the places of parameters because it’s easier to illustrate my point this way; function doesn’t need to change its implementation if the order of its arguments in signature is shuffled):</p><pre>map(f)(List(1, 2, 3))</pre><p>Currying is taking a function of <em>n</em> parameters and turning it into <em>n </em>single-parameter functions. Any <em>n</em>-parameter function can be curried like this; actually, in Haskell this is the only way of achieving a function with more than one parameter. So for example. instead of having a function that takes two numbers and multiplies them, you can only have a function that takes a number and returns a function that takes a number and returns a number. This way, as we said before, <em>(Int, Int) → Int </em>becomes<em> Int → Int → Int</em>. Or if you prefer to write the precedence explicitly, it becomes <em>Int → (Int → Int</em>).</p><p>So our map is now actually a one-parameter function that returns a yet another one-parameter function. This allows us to pass just the first argument like this:</p><pre>map(f) // returns a function List[Int] =&gt; List[String]</pre><p>If we continued on and passed our List(1, 2, 3) to the result of map(f), we would get back a List(“1”, “2”, “3”). But if we<em> stop here</em>, what we get back is a <em>function that takes a list of integers and returns a list of strings</em>. Curried approach gives us a higher-order function that maps <em>typeA </em>→ <em>typeB</em> to <em>Functor[typeA] </em>→ <em>Functor[typeB]. </em>This kind of higher-order function is commonly known as <strong>lift</strong>. It takes a function and “lifts it” so that its operands are put into some context (such as a functor or a monad).</p><p>This means that we can write the signature for map() like this:</p><p><em>(A → B) → F[A] → F[B]</em></p><p>This is the <a href="https://en.wikipedia.org/wiki/Map_(higher-order_function)#Generalization">classic map signature</a> found in many functional programming books and programming languages. Since it’s a chain of two curried functions, we can view it in two ways:</p><ul><li>map takes a function <em>A → B</em> and a functor instance<em> F[A]</em> and it produces another functor instance, <em>F[B] </em>(our classical, non-curried map)</li><li>map takes a function <em>A → B</em> and returns a function<em> F[A] → F[B]</em></li></ul><p>It’s the awesome nature of currying that allows us these two different viewpoints.</p><h4>Problem with functors</h4><p>We saw three different representations of the map function:</p><ul><li>the Scala way: <em>m.map(f)</em></li><li>as a 2-param function: <em>map(m, f)</em></li><li>as a curried function: <em>map(m)(f) </em>or<em> map(f)(m)</em></li></ul><p>Even though second and third way are more common in functional programming world, Scala, being not only FP but also OOP language, decided to go with the first choice since it’s closer to the object-oriented paradigm.</p><p>Now, we know that map() takes a function of <strong>only one </strong>parameter — one that is of the same type as the underlying value inside a functor. For example, map on list of integers takes a function that takes a single Int (but it can return any type).</p><p>However, we also know that using currying we can cheat a little. If we have a function of <em>n</em> parameters, we can curry it and transform it into a function of only one parameter that returns a function of <em>n-1</em> parameters. This would allow us to feed map() with a function of <strong>any number of parameters </strong>(of course, first one would have to be of the appropriate type to match the one wrapped within functor, e.g.<em> Future[Int] </em>could be mapped with a function<em> Int → Whatever → Whatever → Whatever → </em>…).</p><p>Nice idea, but map() doesn’t like it too much.</p><p>Why? A simple example will illustrate the problem. Let’s take a function that adds two integers and curry it:</p><pre>val f = (x: Int) =&gt; (y: Int) =&gt; x + y</pre><p>If we feed this function with a value, we will get back a function of one less parameter than the original, which leaves us with only one parameter (in our case called “y”). So if we feed function <em>f </em>with value 42, we will get back a function that takes a number and adds 42 to it.</p><p>Cool. So let’s feed our curried function to map():</p><pre>val f = (x: Int) =&gt; (y: Int) =&gt; x + y</pre><pre>val result = Future(42).map(f)</pre><pre>// result is Future(x =&gt; x + 42)</pre><p>What we get back is a Future in which our integer number 42 is transformed into a function that takes some integer <em>x</em> and returns <em>x</em>+42<em>.</em> Now this is a bit of a problem. As we said earlier, normally when you curry a function of <em>n</em> parameters and you supply it with the first parameter, you get back a function of <em>n-1 </em>parameters. In case of our function <em>f</em> that adds two numbers, we would get back a function<em> Int → Int</em>. But when we supply that function to map(), <strong>what we get back is not <em>Int → Int</em>, but <em>Future[Int → Int]</em></strong>. We cannot continue applying stuff to the rest of our curried function any more, because map() doesn’t know how to work with a function wrapped inside a future.</p><p>Let me repeat this once more, it’s the key part. So, if we wanted to map our Future with some function of, let’s say, four parameters this time, such as <em>f(a: Int, b: Int, c: Int, d: Int)</em>, we would curry the function into <em>Int→ Int→ Int→ Int </em>and supply it to map(), but that would be the end of it. Map would consume the first parameter, but would not leave us with <em>Int→ Int→ Int</em>. If it did, we could carry on in the same fashion. What it would leave us with is <em>Future[Int → Int → Int] </em>instead.</p><p>What we need now is an <em>applicative functor</em>.</p><h4>Applicative functors</h4><p>Applicative functor (sometimes called simply <em>applicative</em>) is an upgraded version of the common functor we saw earlier. While functors use only single-parameter functions, applicative functors can use functions of any number of arguments. They also introduce the unit/return method which lifts a given type A into F[A]. <em>(Note: Applicative functors also come with a bit different </em><a href="https://en.wikibooks.org/wiki/Haskell/Applicative_functors#Applicative_functor_laws"><em>set of laws</em></a><em> than ordinary functors; I will not go into them here as my intention is simply to explain the idea of applicative functors while leaving “mechanical” parts such as laws to your personal research, once you’re comfortable with the concept)</em></p><p>Let’s consider again some four-parameter function <em>f</em> in curried form. Its signature is <em>Int → Int → Int → Int. </em>Now let’s feed it to map() of some <em>Future[Int]</em>. Result is <em>Future[Int → Int → Int]</em>. We’ve been through this a minute ago. OK, but now something cool happens: our new friend applicative functor comes into play and says: “Hey, so you got your function wrapped into a bit of a context, huh? Not to worry, I know how to apply those kind of wrapped functions. Yes, you heard me well; I can apply functions within a functor context (such as Future, Option or List)”. To avoid confusion, we’ll leave the term “map” to standard functors and use the term “apply” for this new cool function in applicative functors. So, if map is defined as (using curried notation):</p><ul><li><em>map[A, B](f: F[A])(f: A → B): F[B]</em></li></ul><p>then our new method apply() is defined as:</p><ul><li><em>apply[A, B](f: F[A])(f: </em><strong><em>F[A → B]</em></strong><em>): F[B]</em></li></ul><p>There are two more ways to define an applicative functor: replacing <em>apply</em> with the equally powerful <em>map2</em>, or replacing it with a combination of <em>product</em> and <em>map</em>.</p><p>Here are all three definitions:</p><ol><li><em>unit[A](a: A): F[A]<br>apply[A, B](f: F[A])(f: F[A → B]): F[B]</em></li><li><em>unit[A](a: A): F[A]<br>map2[A, B, C](fa: F[A], fb: F[B])(f: (A, B) =&gt; C): F[C]</em></li><li><em>unit[A](a: A): F[A]<br>map[A](fa: F[A]])(f: A =&gt; B): F[B]<br>product[A, B](fa: F[A], fb: F[B]): F[(A, B)]</em></li></ol><p>When I said that methods <em>apply</em> and <em>map2</em> are “equally powerful”, what I meant is that you can express one by using the other. <em>Product</em> is a bit weaker and needs to be accompanied by <em>map</em>. I will not show the translations between these definitions here, but you can find them online (e.g. <a href="https://github.com/robertberry/Functional-Programming-in-Scala-Exercises/blob/master/src/main/scala/com/github/robertberry/fpis/Chapter12.scala">here</a>) or try to work them out yourself.</p><p>We will be using the <em>apply</em> version for now, but then I will show you how it is related to the other two definitions.</p><h4>Solving the functor problem</h4><p>Alright. So what happens if we feed the Future’s map() with function <em>Int → Int → Int → Int</em>? We get back a <em>Future[Int → Int → Int]. </em>Then we can feed its apply() with <em>Future[Int → Int → Int]</em> and get back a F<em>uture[Int → Int]. </em>Finally, we apply the<em> Future[Int → Int]</em> and are left with <em>Future[Int].</em></p><p>Let’s finish our “add by 42” example from earlier. Note that I’m going to write some more pseudo-Scala because there is no method apply() in Future defined in this way. For now, just imagine that such method exists and we’ll explain this predicament later.</p><p>So, in order to feed a two-parameter function to the functor, we would do:</p><pre>val f = (x: Int) =&gt; (y: Int) =&gt; x + y<br>val r1: Future[Int =&gt; Int] = Future(42).map(f)<br>Future(10).apply(r1) // results in Future(52)</pre><p>Do you see what happened here? We took two values of type Future[Int] (Future(42) and Future(10)) and a function <em>f</em> with signature<em> Int → Int </em>and we managed to produce a yet another Future whose underlying value is the result of applying values of our two starting futures to the function <em>f</em>. This is really great. Let’s say you fetch three points of a triangle from a database and wind up with three <em>Future[Int] </em>values. How to calculate the perimeter of the triangle made by those points using function <em>calculate(a: Int, b: Int, c: Int)</em>? You can’t just feed the points to the function because points are not of type Int, but of type Future[Int].</p><p>Using an applicative functor it becomes possible:</p><pre>val f1 = Future(3)<br>val f2 = Future(4)<br>val f3 = Future(5)</pre><pre>val calculate = (a: Int) =&gt; (b: Int) =&gt; (c: Int) =&gt; a + b + c</pre><pre>// btw you can also do:<br>// val calculate = ( (a:Int, b:Int, c:Int) =&gt; a + b + c ).curried</pre><pre>f1.apply(f2.apply(f3.apply(unit(calculate)))) // Future(12)</pre><p>Cool, right? Note that we had to wrap the function into the applicative context by using <em>unit</em> in order for <em>apply </em>to be able to consume it.</p><p>Enough of that pseudo-Scala stuff. Let’s write some actual code. We will use the <a href="https://github.com/scalaz/scalaz">scalaz</a> library:</p><pre>import scalaz._, Scalaz._</pre><pre>val f1 = Future(3)<br>val f2 = Future(4)<br>val f3 = Future(5)</pre><pre>val calculate = (a: Int) =&gt; (b: Int) =&gt; (c: Int) =&gt; a + b + c<br>val area = f1 &lt;*&gt; (f2 &lt;*&gt; (f3 &lt;*&gt; <em>Future</em>(calculate))) // Future(12)</pre><p>Operator &lt;*&gt; is the <em>apply</em> operation. For <em>unit</em>, I simply used the Future constructor.</p><p>Remember how we talked about the three different definitions for applicatives? Let’s see how things work with <em>product + map</em>:</p><pre>import scalaz._, Scalaz._</pre><pre>val f1 = Future(3)<br>val f2 = Future(4)<br>val f3 = Future(5)</pre><pre>val calculate = (a: Int) =&gt; (b: Int) =&gt; (c: Int) =&gt; a + b + c<br>val area = (f1 |@| f2 |@| f3)(calculate)// Future(12)</pre><p>Operator |@| is the <em>product</em> operation. What we did here is that we put together the three applicatives and “merged” them into one (we computed their <em>product</em>) and then we mapped that product with our <em>calculate</em> function. Note that we didn’t explicitly invoke map() because this is how scalaz syntax for applicative product works; combining your applicatives into a product by using |@| results in an ApplicativeBuilder which takes a function to perform on the product (since product + map is a very common use case). Pay attention to one detail: <em>calculate</em> can’t be curried here, since the applicative product takes an uncurried, multi-parameter function (in this case arity 3). I</p><p>If it’s easier for you to reason about the whole process by using the <em>product</em> definition instead of by using the <em>apply </em>definition, that’s actually pretty normal. I have shown you both ways, you’re free to pick up whichever you prefer. Anything you can do with <em>unit</em> + <em>apply</em>, you can do with <em>unit</em> + <em>product</em> + <em>map</em> and vice versa. Same goes for the third definition, <em>unit + map2 </em>(I will let you investigate that one on your own; it’s been removed from scalaz7 anyway, so if you decide to skip it that’s fine).</p><p>By the way, astute reader will notice that the product version is actually doable in regular Scala. Yup, that’s a <em>zip</em> right there.</p><pre>val area = (f1 zip f2 zip f3) map { <br>  case ((a, b), c) =&gt; calculate(a, b, c) <br>} // Future(12)</pre><p>A bit clumsy, but doable.</p><h4>Conclusion</h4><p>“Regular” functors are basically wrappers for values of some type. List[Int], Future[String] and Option[Whatever] are examples of functors.</p><p>Applicative functors are a bit more sophisticated — they know how to apply a function wrapped in functor context. For example, given a Future[Int] functor, we can apply a function <em>Future[Int → Int]</em> to it, while regular map() in regular functors only knows how to apply <em>Int → Int.</em> Or, you can look at it this way: on top of regular functor’s <em>map</em> functionality, applicative functor adds the <em>unit </em>function, which lifts an ordinary A into functor context F[A], and <em>product</em> function, which can be used to combine multiple functors into one.</p><p>So, there are multiple ways of describing an applicative functor that lead to the same basic principle. Applicative functor is like a functor, but:</p><ul><li>applicative functor can apply functions of more than one parameter</li><li>applicative functor can apply functions wrapped inside a functor context</li><li>applicative functor can combine multiple functors into one product</li><li>etc.</li></ul><p>And now one more interesting point before we finish:</p><p>You may or may not already know something about monads. Well, monads go one step further and provide you with an even more powerful operation. Here they are in comparison, all three of them (I’m omitting <em>unit</em> because it’s not needed for making this point):</p><ul><li><strong>functor</strong>: <em><br>map(f: F[A])(f: A → B): F[B]</em></li><li><strong>applicative functor</strong>:<em><br>apply(f: F[A])(f: F[A → B]): F[B]</em></li><li><strong>monad</strong>:<br><em>flatMap(f: F[A])(f: A → F[B]): F[B]</em></li></ul><p>Just like applicatives can use other definitions (e.g. <em>product + map</em> instead of <em>apply</em>), same goes for monads (e.g. <em>flatten + map</em> instead of <em>flatMap</em>). Monads are the most powerful; they can be “conditioned”, which means that one monad can take action depending on the result of the previous monadic operation. Or, if you prefer — they can work in series, whereas applicatives work in parallel. See that <em>f: A → F[B] </em>in monad definition? That’s the part that enables this dependency; it says “take A from monad F[A] and compute monad F[B] based on it”.</p><p>So if you have e.g. <em>n</em> asynchronous requests (e.g. database queries) that result in <em>n</em> Futures, you should pick a proper abstraction based on your needs:</p><ul><li>if your Futures don’t depend on each other, use an applicative (you can e.g. put them all into one product and map each result with a function that handles success/failure)</li><li>if your Futures do depend on each other, e.g. you want to call them in series and stop on first success or first failure, then use a monad (it allows you to flatMap a future with a function that examines its value and performs the next monadic operation based on it)</li></ul><p>This is why you can only build a parser for context-sensitive grammars by using monads, while for context-free grammars it’s enough to use applicatives.</p><p>OK, that’s all for now. As usual, in case you feel something is unclear, confusing, misleading or incorrect, drop me a comment here or throw me an email on sinisalouc@gmail.com. Also feel free to find me on <a href="https://twitter.com/sinisalouc">Twitter</a>.</p><p>Cheers!</p><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a>family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp;sponsorship</a> opportunities.</blockquote><blockquote>To learn more, <a href="https://goo.gl/4ofytp">read our about page</a>, <a href="http://bit.ly/HackernoonFB">like/message us on Facebook</a>, or simply, <a href="https://goo.gl/k7XYbx">tweet/DM @HackerNoon.</a></blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9af535b1440" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/functors-and-applicatives-b9af535b1440">Functors and Applicatives</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Methods as functions (or, what exactly is “eta expansion”?)]]></title>
            <link>https://medium.com/@sinisalouc/on-method-invocations-or-what-exactly-is-eta-expansion-1019b37e010c?source=rss-690955769210------2</link>
            <guid isPermaLink="false">https://medium.com/p/1019b37e010c</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Sinisa Louc]]></dc:creator>
            <pubDate>Thu, 02 Jun 2016 15:08:13 GMT</pubDate>
            <atom:updated>2017-02-25T18:43:40.314Z</atom:updated>
            <content:encoded><![CDATA[<p>A few days ago I stumbled upon a StackOverflow question regarding this stuff and while writing my answer I noticed that I wrote a respectable chunk of text. Which is a good indicator for a blog post. Oh and by the way, in case you’re not familiar with any of my previous work, this post will be mostly revolving around Scala (although the concepts presented are quite general in functional programming).</p><p>First we will see what’s the difference between no-parenthesis and empty-parenthesis methods. We will see what role this difference plays when converting methods to functions. Eta-expansion as a mechanism for transforming methods into functions will be explained, as well as techniques for manual conversion. Finally, partially applied functions and curried functions are explained in the context of the problem at hand.</p><h4>If it’s empty, it still exists</h4><p>Let’s say we have these two creatively named methods:</p><pre>def methodA(s: String) = ???<br>def methodB(f: () =&gt; String) = ???</pre><p>We want to see which invocations of these methods pass and which fail when we feed them with different values for parameters.</p><p>Let’s start from this very simple method <em>f</em>:</p><pre>def f = &quot;foo&quot;</pre><pre>methodA(f)<br>methodB(f) // error!</pre><pre>methodA(f()) // error!<br>methodB(f()) // error!</pre><p>Since <em>methodA()</em> takes a String, it will have no problems taking <em>f</em> as a parameter. Instead of as a method, our <em>f</em> can basically be viewed as a value whose evaluation is performed every time it’s accessed. If we had a <em>val</em> instead, it would only be evaluated once (and <em>lazy val</em> would postpone that evaluation until the point of usage). This is what they teach you in every Scala book. If <em>f</em> had a side-effect, that effect would be performed twice in our example, whereas having <em>f</em> as a val would result in side-effect being performed only once — at the point of definition of <em>f</em>. OK, nothing new here.</p><p>Onto method B. Since it’s expecting a function (although a weird one, from “nothing” to String), it cannot tolerate our pure String being passed. Compiler’s message is pretty clear: “<em>Type mismatch, expected () ⇒ String, actual: String</em>”.</p><p>The other two invocations are completely wrong. When we say <em>f()</em>, compiler thinks we are trying to access a certain char within <em>f</em> (because <em>f</em> is actually a string “<em>foo</em>”) and tells us that methods A and B take a string, not a char. And even if they were taking a char, we would need to provide an index of the char we are trying to fetch from <em>f</em>.</p><p>Now, let’s make things more interesting. Let’s add a seemingly trivial and irrelevant addition to our method <em>f</em> (we can call the new version <em>f2</em>):</p><pre>def f2<strong>()</strong> = &quot;foo&quot;</pre><p>We added the empty parenthesis. What implications does this have? Well, first of all, we can actually invoke our method the good old fashioned way — by writing <em>f2()</em>. We couldn’t have done this with <em>f </em>because our <em>f</em> was treated like a string value, but things are a bit different now. Expression <em>f2()</em> behaves exactly as you would expect it to — it invokes the <em>f2</em> method and results in the string “<em>foo</em>”.</p><p>What if we write just <em>f2</em>? Hold on, let’s try to invoke our evaluation methods and see what happens:</p><pre>methodA(f2())<br>methodB(f2()) // error!</pre><pre>methodA(f2)<br>methodB(f2)</pre><p>OK, first two invocations should be pretty obvious. Invoking f2() results in a string, which is fine for method A, but not fine for method B which takes a function.</p><p>However, other two invocations <strong>both worked fine</strong>! If this is not a surprise to you, well, either you are already familiar with this mechanism in Scala or you are not paying enough attention :) I mean, these two methods have parameters of different types, and yet they can both take the same value. Is our value <em>f2</em> both a string and a function at the same time? Of course not. Actually, it’s neither. It’s not really a value at all; it’s a <em>method</em> that returns a string. In theory, neither of these two invocations should have succeeded. This is where Scala compiler comes into play.</p><p>First invocation, <em>methodA(f2)</em>, works because the compiler assumes that when we said <em>f2</em> what we actually wanted was <em>f2()</em>. It gives a warning “<em>empty-paren method accessed as parameterless</em>”. While having a method <em>f</em> and accessing it as <em>f()</em> results in a completely different thing (invoking <em>apply()</em> on a String, which results in a Char once we provide it with index), having it the other way around — method <em>f2()</em> accessed as <em>f2</em> — results in the same thing as <em>f2()</em>. This is defined in the <a href="http://docs.scala-lang.org/style/method-invocation.html#arity-0">style guide</a>, but is not really encouraged, and with a good reason — it can confuse people. To spare yourself the confusion, my advice is to always invoke the method as it is defined. If parameterless, invoke it without parenthesis. If empty-parenthesised, invoke it with empty parenthesis. Former is commonly used for getters of class fields whose value needs to be re-calculated every time (such as <em>currentAccountBalance</em>) and latter for functions with side-effects (such as <em>println()</em>).</p><h4>Eta-conversions</h4><p>That was the first invocation, <em>methodA(f2). </em>Now, about that second one, <em>methodB(f2)</em>. This is where things get a bit more interesting. What Scala compiler just performed for us is called <strong>eta-expansion</strong>. There are two directions for this “eta operation”, as you will see soon. In literature, direction of <em>eta-expansion</em> is also sometimes called <em>eta-abstraction</em>, opposite direction is called <em>eta-reduction</em>, and they are both referred to under common term <em>eta-conversion</em>.</p><p>The idea behind eta-expansion is pretty simple. Having a function <em>f(x)</em>, we normally refer to the function itself as <em>f</em>. For example, imagine we need to pass it to another function; we would pass simply <em>f</em>. Now, if instead of passing <em>f</em> we passed <em>x ⇒ f(x)</em>, nothing would change, would it? Take the square function for example. We give it a 4, it returns a 16. Having this function is completely the same as having function <em>x ⇒ sqr(x).</em> We give it a 4, it returns a 16. We just “wrapped” our <em>sqr</em> function with another layer, resulting in another function. We can do this indefinitely:</p><pre>val sqr = (x: Int) =&gt; x * x<br>val sqr2 = (x: Int) =&gt; sqr(x)<br>val sqr3 = (x: Int) =&gt; sqr2(x)<br>val sqr3_expandedVersion = (x: Int) =&gt; ((x: Int) =&gt; sqr(x))(x)<br><br>println(sqr(4))<br>println(sqr2(4))<br>println(sqr3(4))<br>println(sqr3_expandedVersion(4))</pre><p>They all print 16. Eta-reduction is simply going in other direction — from <em>sqr3</em> towards <em>sqr</em>. By the way, don’t mind the “expanded version” in the code; it looks a bit complicated, but if you take a closer look you’ll see that it is merely injecting the definition of <em>sqr2</em> into <em>sqr3</em> so that it only depends on <em>sqr</em>. It’s just showing how the function grows more and more, but retains the same functionality.</p><p>Eta-expansion is what compiler does “behind the scenes” when it notices that you need a function, but are provided a method. Here’s a simplified version of what it does:</p><pre>// given a method:<br>def someMethod() = ???<br>// it&#39;s easy to convert it to a function using eta-expansion:<br>val someFunction = () =&gt; someMethod()</pre><pre>// if there are parameters, it&#39;s still the same principle:<br>def someMethod(x: Int, y: String) = ???<br>val someFunction = (x: Int, y: String) =&gt; someMethod(x, y)</pre><p>Simple, but powerful.</p><h4>Partially applied functions</h4><p>There are times when compiler is not expecting a function so it will not automatically convert the method into a function. For example, let’s revisit our method <em>f2()</em> and try to define a corresponding function with same functionality:</p><pre>def f2() = &quot;foo&quot;<br>val f2fun = f2 // f2fun is a string, not a function!</pre><p>What happened? If you remember that stupid confusing automatic conversion from earlier, you will recall that it is allowed to invoke a parameterless method (that is, an empty-parenthesised method) without the parenthesis. OK, we agreed we would avoid doing this deliberately in our code in order to avoid confusion, but what do we do about the existing convention in the compiler that interprets our <em>f2</em> as <em>f2()</em>? How do we turn the method <em>f2()</em> into a function value <em>f2</em>?</p><p>Well, there are two things we can do:</p><ul><li>explicitly declare the type of value to be a function</li><li>treat the method as a partially applied function</li></ul><pre>def f2() = &quot;foo&quot;<br>val f2fun1 = f2               // f2fun is a string, not a function<br>val f2fun2: () =&gt; String = f2 // however, this works!<br>val f2fun3 = f2 _             // this too!</pre><p>Explicitly declaring the type of value is a nice way to go. You are telling the compiler “cut it out with your automatic parameterless invocation mumbo-jumbo and turn this method into a function”.</p><p>But treating the method as a <em>partially applied function</em> is, in my opinion, an even more elegant solution. If you’re not familiar with partially applied functions (and a closely related technique, <em>currying</em>), then it would be a wise thing to consult <a href="http://www.tutorialspoint.com/scala/partially_applied_functions.htm">some</a> <a href="http://www.artima.com/pins1ed/functions-and-closures.html#8.6">online</a> <a href="http://danielwestheide.com/blog/2013/01/30/the-neophytes-guide-to-scala-part-11-currying-and-partially-applied-functions.html">sources</a>.</p><p>Shortly put, partially applying a function is a way to… well, partially apply a function :) Seriously though, if we have a function that takes three parameters, x, y and z, we can only apply the first one and as a result get a function of two parameters. Or we can apply the first two and get a function of only one parameter. For example, having a function that takes two integers and adds them, we can apply only the first one, e.g. 42, and as a result we will get a function that adds the input number to 42:</p><pre>val add: (Int, Int) =&gt; Int = (a: Int, b: Int) =&gt; a + b<br>val add42: Int =&gt; Int = <strong>add(42, _)</strong><br>println(add42(8)) // 50</pre><p>We “fixed” the first parameter and only allowed the second one to be specified by the user. Note that if you don’t explicitly define <em>add42</em> to be of type Int =&gt; Int, you will need to explicitly define the type of the unused parameter: <em>add(42, _: Int)</em>.</p><p>Currying is a similar principle. Main idea with currying is to separate a function of <em>n</em> parameters into <em>n</em> functions of one parameter. This is how all functions with 2-or-more parameters are treated in Haskell; you cannot have a function of more than one parameter. If you need a function of, say, three parameters, what you do is you define a function of one parameter returning a function of one parameter that returns a function of one parameter. Function f(a, b, c) in Haskell must be defined as a function returning a function which returns a function, and it’s invoked as f(a)(b)(c).</p><p>OK, small digression, back to Scala. Currying works just the same in Scala, but is not mandatory. Note that if we curry a function, there’s no need for the underscore thingy; with partially applied functions it’s needed because otherwise compiler will rightfully complain that <em>add()</em> takes two parameters, but with currying we are simply providing only the first parameter, which is completely valid:</p><pre>val add: Int =&gt; Int =&gt; Int = (a: Int) =&gt; (b: Int) =&gt; a + b</pre><pre>val add42: Int =&gt; Int = <strong>add(42)</strong><br>println(add42(8)) // 50</pre><pre>val add42and8: Int = <strong>add(42)(8)</strong><br>println(add42and8) // 50</pre><p>One more thing to keep in mind (I’m risking to lose you here, but here goes) — if you have a method with <em>empty parenthesis</em> and you want to turn it into a function, either of these two techniques will work. However, if you have a method <em>without parenthesis</em>, then explicit type won’t work:</p><pre>def foo() = &quot;foo&quot;<br>val foo2 = foo _<br>val foo3: () =&gt; String = foo<br><br>def bar = &quot;bar&quot;<br>val bar2 = bar _<br>val bar3: () =&gt; String = bar <strong>// error</strong></pre><p>Don’t get discouraged; there’s no need to remember these compiler quirks. Important things that I’m hoping you will get out of this article are listed below.</p><h4>Summary</h4><p>Alright, here’s a short recap of the information presented in this article:</p><ul><li><em>Methods </em>are not the same as <em>functions:</em> functions are values just like integers, strings or other objects and they can be passed around, returned, kept inside collections etc. Methods on the other hand are not values; they don’t have a type and cannot exist on their own (they are an attribute of a structure in which they are defined, e.g. a class, object or trait). Note that methods must be defined using the <em>def</em> keyword, while functions can be defined like any other value — by using def, val or lazy val, in which case the keyword determines whether the value is evaluated every time, only once or only once but at the point of usage.</li><li>There is a difference between methods with <em>no parenthesis</em> and methods with <em>empty parenthesis:</em> former are basically values, but re-evaluated upon every access, while latter are methods as we know them. My strong advice is to <em>invoke them as they are defined </em>(if there are empty parens in definition, put them in invocation too; this way you don’t have to remember what happens if <em>f</em> is invoked as <em>f()</em> and vice versa).</li><li><em>Eta-expansion </em>is a simple technique for wrapping functions into an extra layer while preserving identical functionality (e.g. from <em>sqr </em>to<em> x ⇒ sqr(x)</em>) and it’s performed by the compiler to create functions out of methods.</li><li>When automatic eta-expansion fails, you can use two techniques to covert a method into a function: <em>explicitly</em> <em>declare type of value to be a function</em> or <em>treat the method as a partially applied function </em>by putting an underscore after method name, which means all of its parameters are transferred to function parameters.</li></ul><p>That’s all for now. As usual, I’m looking forward to your comments and feedback on sinisalouc@gmail.com. Also feel free to hit me up on <a href="https://twitter.com/sinisalouc">Twitter</a>.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1019b37e010c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overcoming type erasure in Scala]]></title>
            <link>https://medium.com/@sinisalouc/overcoming-type-erasure-in-scala-8f2422070d20?source=rss-690955769210------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f2422070d20</guid>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Sinisa Louc]]></dc:creator>
            <pubDate>Wed, 04 May 2016 08:27:47 GMT</pubDate>
            <atom:updated>2018-07-18T08:25:27.067Z</atom:updated>
            <content:encoded><![CDATA[<p>This article aims to show a couple of techniques to tackle some common problems caused by type erasure in Scala.</p><h4>Introduction</h4><p>Scala has a really strong type system. Existential types, structural types, nested types, path-dependant types, abstract and concrete type members, type bounds (upper, lower, view, context), use-site and declaration-site type variance, support for type polymorphism (subtype, parametric, F-bounded, ad-hoc), higher-kinded types, generalized type constraints… And the list goes on.</p><p>But even though Scala’s type system is theoretically very strong, in practice some type-related features are weakened by the restrictions and limitations of its runtime environment — that’s right, I’m looking at you, <a href="https://docs.oracle.com/javase/tutorial/java/generics/erasure.html">type erasure</a>.</p><p>What is type erasure? Well, simply put, it’s a procedure performed by Java and Scala compilers which removes all generic type information after compilation. This means that we are not able to differentiate between, say, List[Int] and List[String] at runtime. Why does the compiler do this? Well, because Java Virtual Machine (the underlying runtime environment that runs both Java and Scala) doesn’t know anything about generics.</p><p>What happens is that type parameters in a generic class get replaced either with Object or its upper bound. For example:</p><pre>class Foo[T] {<br>  val foo: T<br>}</pre><pre>class Bar[T &lt;: Something] {<br>  val bar: T<br>}</pre><p>becomes</p><pre>class Foo {<br>  val foo: Object<br>}</pre><pre>class Bar {<br>  val bar: Something<br>}</pre><p>So you see, runtime has no idea about the actual class that a generic class was parameterized with. In our example, it only sees raw Foo and Bar.</p><p>Don’t think that type erasure is a product of someone’s incompetence or ignorance or whatever. It’s not bad design (which would suggest it was a product of someone not being smart enough or competent enough); it’s a deliberate trade-off. Not only did it help with <a href="https://blogs.oracle.com/darcy/entry/kinds_of_compatibility">source, binary and behavioral compatibility</a> in the earlier Java days, but it also helps with some advanced type system mechanisms, such as <a href="https://typelevel.org/blog/2016/08/21/hkts-moving-forward.html">higher-kinded types</a> (thanks <a href="https://medium.com/@gabriel.claramunt?source=responses---------7-31--------------------">Gabriel Claramunt</a> for pointing this out).</p><p>Now let’s see what are some handy ways that we can handle the downsides of type erasure in Scala.</p><h4>How it works (or doesn’t work)</h4><p>Here’s one simple example of type erasure:</p><pre>object Extractor {<br>  def extract[T](list: List[Any]) = list.flatMap {<br>    case element: T =&gt; Some(element)<br>    case _ =&gt; None<br>  }<br>}<br><br>val list = List(1, &quot;string1&quot;, List(), &quot;string2&quot;)<br>val result = Extractor.extract[String](list)<br>println(result) // List(1, string1, List(), string2)</pre><p>Method extract() takes a list of all kinds of objects; since it holds objects of type Any, we can put numbers, booleans, strings, bananas, oranges, whatever. By the way, seeing List[Any] in a piece of code should be an instant “code smell”, but let’s forget about best practices for a second and focus on the problem with type erasure.</p><p>So, our desire is to have a method that takes a list of mixed objects and extracts only objects of certain type. We can choose this type by parameterizing the method extract() with it. In the given example the chosen type is String, which means that we will try to extract all strings from a given list.</p><p>From a strictly language point of view (without going into runtime details), this code is reasonable. We know that pattern matching is able to figure out the type of a given object without problems by deconstructing it. However, due to program being executed on JVM, all generic types are erased after compilation. Therefore pattern matching cannot really get far; everything beyond the “first level” of type is erased. Matching our variable directly on Int or String (or any non-generic type, such as MyNonGenericClass) would work fine, but matching it on T, where T is a generic parameter, cannot work. Compiler will give us a warning saying “<em>abstract type pattern T is unchecked since it is eliminated by erasure</em>”.</p><p>To provide some assistance with these situations, Scala introduced Manifests somewhere around version 2.7. However, they had problems with not being able to represent certain types so Scala 2.10. deprecated them in favour of the more powerful <a href="http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html">TypeTags</a>.</p><p>Type tags are divided into three separate types:</p><ul><li>TypeTag</li><li>ClassTag</li><li>WeakTypeTag</li></ul><p>Even though this is the official classification from the documentation, better division in my opinion would be something like:</p><ul><li>TypeTag:<br>- “classic”<br>- WeakTypeTag</li><li>ClassTag</li></ul><p>I’m trying to make a point that TypeTag and WeakTypeTag are actually two flavours of the same thing with only one significant difference (as we’ll show later), while ClassTag is a quite different construct.</p><h4>ClassTag</h4><p>Let’s get back to our extractor example and see how we can fix the type erasure problem. All we’re going to do now is add a single implicit parameter to the extract() method:</p><pre>import scala.reflect.ClassTag</pre><pre>object Extractor {<br>  def extract[T](list: List[Any])<strong>(implicit tag: ClassTag[T])</strong> =<br>    list.flatMap {<br>      case element: T =&gt; Some(element)<br>      case _ =&gt; None<br>    }<br>}</pre><pre>val list: List[Any] = List(1, &quot;string1&quot;, List(), &quot;string2&quot;)<br>val result = Extractor.extract[String](list)<br>println(result) // List(string1, string2)</pre><p>And voila! Suddenly the print statement displays “<em>List(string1, string2)</em>”. In your face, type erasure. Note that we can also use context bound syntax here:</p><pre>// def extract[T](list: List[Any])(implicit tag: ClassTag[T]) =<br>def extract<strong>[T : ClassTag]</strong>(list: List[Any]) =</pre><p>I will use the standard syntax simply to make the code as clear as possible, without any extra syntax sugar.</p><p>So, how does it work? Well, the thing is that when we require an implicit value that is of type ClassTag, compiler will create this value for us. <a href="http://lampwww.epfl.ch/~hmiller/scaladoc/library/scala/reflect/ClassTag.html">Documentation</a> says:</p><blockquote>If an implicit value of type u.ClassTag[T] is required, the compiler will make one up on demand.</blockquote><p>So, the compiler is happy to provide us with an implicit instance of a needed ClassTag, we just need to ask. This mechanism will also be used with TypeTag and WeakTypeTag.</p><p>OK, we have our implicit ClassTag value available in extract() method (thanks, compiler). What happens once we’re inside the method body? Look at the example once again — not only did the compiler automatically provide us with the value for our implicit parameter tag, which is nice enough, but we <strong>never needed to use the parameter itself</strong>. We never had to do anything with the “tag” value. It’s the mere existence of it that allowed our pattern matching to successfully match the String elements in our list. OK, that’s pretty nice of the compiler, but it feels like there’s too much “magical stuff” going on. Let’s see that in more detail.</p><p>We can check the <a href="http://The%20compiler%20tries%20to%20turn%20unchecked%20type%20tests%20in%20pattern%20matches%20into%20checked%20ones%20by%20wrapping%20a%20%28_:%20T%29%20type%20pattern%20as%20ct%28_:%20T%29,%20where%20ct%20is%20the%20ClassTag[T]%20instance.">docs</a> in search for an explanation. Indeed, it’s hidden here:</p><blockquote>Compiler tries to turn unchecked type tests in pattern matches into checked ones by wrapping a (_: T) type pattern as ct(_: T), where ct is the ClassTag[T] instance.</blockquote><p>Basically what happens is that if we provide the compiler with an implicit ClassTag, it will rewrite the condition(s) in pattern matching to use the given tag as an extractor. Our condition:</p><pre>case element: T =&gt; Some(element)</pre><p>gets translated by the compiler (if there is an implicit tag in scope) into this:</p><pre>case (element @ tag(_: T)) =&gt; Some(element)</pre><p>In case you never saw the “@” construct before, it’s just a way of giving a name to the class you’re matching, for example:</p><pre>case Foo(p, q) =&gt; // we can only reference parameters via p and q<br>case f @ Foo(p, q) =&gt; // we can reference the whole object via f</pre><p>If there is no available implicit ClassTag for type T to be used, compiler will be crippled (due to lack of type information) and it will issue a warning that our pattern matching will suffer from type erasure on type T. Compilation won’t break, but don’t expect compiler to know what T is when we get to pattern matching (since it will be erased by the JVM at runtime). If we do provide an implicit ClassTag for type T, compiler will be happy to provide a proper ClassTag at compile-time as we have seen in our example. The tag will bring along the information about T being a String and type erasure cannot touch it.</p><p>Looks good, doesn’t it? But there’s one important weakness. If we wanted to differentiate our types on a higher level and get values of List[Int] from our initial list while ignoring e.g. List[String], we would not be able to do so:</p><pre>val list: List[List[Any]] = List(List(1, 2), List(&quot;a&quot;, &quot;b&quot;))<br>val result = Extractor.extract[List<strong>[Int]</strong>](list)<br>println(result) // List(List(1, 2), <strong>List(a, b)</strong>)</pre><p>Whoops! We wanted to extract only List[Int], but we got a List[String] too. Class tags <strong>cannot differentiate on a higher level.</strong> Only on the first one. This means that our extractor can differentiate between e.g. sets and lists, but it cannot tell apart one list from another (e.g. List[Int] vs List[String]). Of course, it’s not just the lists — this goes for all generic traits/classes.</p><h4>TypeTag</h4><p>Where ClassTag fails, TypeTag succeeds gloriously. It can differentiate a List[String] from a List[Integer]. It can go deeper too, such as differentiating List[Set[Int]] from List[Set[String]. This is possible because TypeTag has richer information about the generic type at run time. We can easily get the full path of the type in question, as well as all the nested types (if there are any). To get this information, you just need to invoke tpe() on a given tag.</p><p>Here’s an example. The implicit tag parameter is provided by the compiler, just like with ClassTag. Pay attention to the “args” argument — it’s the one that contains additional type information which ClassTag doesn’t have (information about List being parameterized by Int).</p><pre>import scala.reflect.runtime.universe._</pre><pre>object Recognizer {<br>  def recognize[T](x: T)<strong>(implicit tag: TypeTag[T])</strong>: String =<br>    tag.tpe match {<br>      case TypeRef(utype, usymbol, args) =&gt;<br>        List(utype, usymbol, args).mkString(&quot;\n&quot;)<br>    }<br>}<br><br>val list: List[Int] = List(1, 2)<br>val result = Recognizer.recognize(list)<br>println(result)</pre><pre>// prints:<br>//   scala.type<br>//   type List<br>//   List(<strong>Int</strong>)</pre><p>(You may need to add a <a href="http://mvnrepository.com/artifact/org.scala-lang/scala-reflect">dependency</a>).</p><p>I introduced a new object here — a Recognizer. What happened to the good-old Extractor? Well, sad news. We cannot implement an Extractor using TypeTags. Good thing about them is having more information about the type, such as knowing about the higher types (that is, being able to differentiate List[X] from List[Y]), but their downside is that they <strong>cannot be used on objects at runtime</strong>. We can use the TypeTag to get information about a certain <em>type</em> at runtime, but we cannot use it to find out the type of some <em>object</em> at runtime. Do you see the difference? What we passed to recognize() was a straightforward List[Int]; it was the declared type of our List(1,2) value. But if we declared our List(1, 2) as a List[Any], TypeTag would tell us that we passed a List[Any] to it.</p><p>OK, here are the two main differences between ClassTags and TypeTags in one place:</p><ol><li>ClassTag doesn’t know about “higher type”; given a List[T], a ClassTag only knows that the value is a List and knows nothing about T.</li><li>TypeTag knows about “higher type” and has a much richer type information, but cannot be used for getting type information about values at runtime. In other words, TypeTag provides <strong>runtime</strong> <strong>information</strong> <strong>about the type </strong>while<strong> </strong>ClassTag provides <strong>runtime</strong> <strong>information about the value</strong> (more specifically, information that tells us what is the actual type of the value in question at runtime).</li></ol><p>There’s one more thing worth mentioning regarding the difference between ClassTag and (Weak)TypeTag: ClassTag is a classical good old type class. It comes bundled with a separate implementation for each type, which makes it a standard <a href="https://medium.com/@sinisalouc/ad-hoc-polymorphism-and-type-classes-442ae22e5342#.41sf94ijq">type class pattern</a>. On the other hand, (Weak)TypeTag is a bit more sophisticated and to use it we need to have a special import in our code, as you may have noticed in the snippet given earlier. We need to import the <a href="http://www.scala-lang.org/api/current/scala-reflect/index.html#scala.reflect.api.Universe@WeakTypeTag%5BT%5DextendsEqualswithSerializable">universe</a>:</p><blockquote>Universe provides a complete set of reflection operations which make it possible for one to reflectively inspect Scala type relations, such as membership or subtyping.</blockquote><p>Don’t worry, all you need to do is to simply import the correct universe, and in case of (Weak)TypeTag that is <em>scala.reflect.runtime.universe._</em> (<a href="http://www.scala-lang.org/api/current/scala-reflect/index.html#scala.reflect.runtime.package">docs</a>).</p><h4>WeakTypeTag</h4><p>You are probably under the impression that TypeTag and WeakTypeTag are quite similar as all the differences so far were explained in respect to the ClassTag. And that is correct; they are indeed two variants of the same tool. But, there is an important difference.</p><p>We saw that TypeTag is smart enough to examine a type as well as its type parameters, then their type parameters etc. However, all those types were <em>concrete</em>. If a type is <em>abstract</em>, TypeTag will not be able to resolve it. This is where WeakTypeTag comes into play. Let’s revise the TypeTag example for a second:</p><pre>val list: List<strong>[Int]</strong> = List(1, 2)<br>val result = Recognizer.recognize(list)</pre><p>See that Int over there? It could have been any other concrete type, such as String, Set[Double] or MyCustomClass. But if you have an abstract type, you need a WeakTypeTag.</p><p>Here’s an example. Note that we need a reference to an abstract type so we will simply wrap everything in an abstract class.</p><pre>import scala.reflect.runtime.universe._</pre><pre><strong>abstract class SomeClass[T]</strong> {<br><br>  object Recognizer {<br>    def recognize[T](x: T)(implicit tag:<strong> WeakTypeTag[T]</strong>): String =<br>      tag.tpe match {<br>        case TypeRef(utype, usymbol, args) =&gt;<br>          List(utype, usymbol, args).mkString(&quot;\n&quot;)<br>      }<br>  }<br><br>  val list: <strong>List[T]</strong><br>  val result = Recognizer.recognize(list)<br>  println(result)<br>}<br><br><strong>new SomeClass[Int] </strong>{ val list = List(1) }</pre><pre>// prints:<br>//   scala.type<br>//   type List<br>//   List(<strong>T</strong>)</pre><p>Resulting type is a List[T]. If we had used a TypeTag instead of a WeakTypeTag, compiler would have complained that there is “<em>no TypeTag available for List[T]</em>”. So, you can look at WeakTypeTag as a sort of a superset of the TypeTag.</p><p>Note that WeakTypeTag tries to be as concrete as possible, so if there is a type tag available for some abstract type, WeakTypeTag will use that type tag and thus make the type concrete instead of leaving it abstract.</p><h4>Conclusion</h4><p>Before we finish, let me mention that each type tag can also be instantiated explicitly using available helpers:</p><pre>import scala.reflect.classTag<br>import scala.reflect.runtime.universe._<br><br>val ct = <strong>classTag</strong>[String]<br>val tt = <strong>typeTag</strong>[List[Int]]<br>val wtt = <strong>weakTypeTag</strong>[List[Int]]<br><br>val array = ct.newArray(3)<br>array.update(2, &quot;Third&quot;)<br><br>println(array.mkString(&quot;,&quot;))<br>println(tt.tpe)<br>println(wtt.equals(tt))<br><br>//  prints:<br>//    null,null,Third<br>//    List[Int]<br>//    true</pre><p>That’s all. We saw three constructs, ClassTag, TypeTag and WeakTypeTag, that will get you through most of your type erasure troubles in your everyday Scala life. Note that using tags (which is basically <a href="http://docs.scala-lang.org/overviews/reflection/overview.html">reflection</a> under the hood) can slow things down and make the generated code significantly bigger, so don’t go around adding implicit type tags all over your library to make the compiler smarter “just in case” and for no practical reason. Save them for when you really need them. And when you do need them, they will provide a powerful weapon against JVM’s type erasure.</p><p>As usual, feel free to contact me on sinisalouc@gmail.com or <a href="https://twitter.com/sinisalouc">find me on Twitter.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f2422070d20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ad-hoc polymorphism and type classes]]></title>
            <link>https://medium.com/@sinisalouc/ad-hoc-polymorphism-and-type-classes-442ae22e5342?source=rss-690955769210------2</link>
            <guid isPermaLink="false">https://medium.com/p/442ae22e5342</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Sinisa Louc]]></dc:creator>
            <pubDate>Sat, 09 Jan 2016 19:24:41 GMT</pubDate>
            <atom:updated>2017-04-20T08:27:40.585Z</atom:updated>
            <content:encoded><![CDATA[<p>This article explains what ad-hoc polymorphism is, what kind of problems it solves and how to implement the whole thing using the type class pattern.</p><h4>Types of polymorphism</h4><p>We’ll start from <em>parametric polymorphism</em>. Say we have some list of items; this could be a list of integers, doubles, strings, whatever. Now consider a method head() which returns the first item from that list. This method doesn’t care if the item is of type Int, String, Apple or Orange. Its return type is the one list is parameterized with and its implementation is <strong>the same </strong>for all types: “return first item”.</p><p>Unlike parametric polymorphism, <em>ad-hoc polymorphism</em> is bound to a type. Depending on the type, <strong>different implementations</strong> of the method are invoked. Method overloading is one example of ad-hoc polymorphism. For example, you can have two versions of method that appends two items — one that takes two integers and adds them, and one that takes two strings and concatenates them. You know, 2 plus 3 is 5, but “2” plus “3” is “23”.</p><p>There’s also a third kind of polymorphism, <em>subtyping polymorphism</em>, in which subclasses provide different implementations of some superclass method. Unlike the ad-hoc polymorphism where the decision on which implementation is being invoked is made at compile time, in subtyping polymorphism it is made at run time (in case of parametric polymorphism there is just one implementation so no decision is being made there).</p><p>OK, let’s take a closer look at ad-hoc polymorphism and leave the other two for some other time. Now, I already mentioned overloading as one way to achieve ad-hoc polymorphism; each “version” of the method will take different parameters, and when the method is invoked the correct implementation will be chosen based on the type of provided parameters. But let’s say we have a different scenario — let’s say we want to have<strong> just one</strong> method (we can call it appendItems()) and we want this method to take two “appendable”<em> </em>items. If invoked with integers, they should be appended using addition. If invoked with strings, they should be appended using concatenation. We could also implement it for various other types, but for our example Integer and String will be enough.</p><h4>How to append ducks</h4><p>So, we want the appendItems() method to take two instances of something “appendable” and perform the append operation upon them. We also want this operation to have different implementations for different appendables. For integers append means addition and for strings it means concatenation. This is ad-hoc polymorphism at its best.</p><p>Note that our method should have just one implementation — no overloading or overriding! So how can it perform different operations for different types? Well, the idea is that appendItems() should not even know how the append operation is implemented; it should just invoke it. Here’s the method:</p><pre>def appendItems[A](a: A, b: A) = a append b</pre><p>This is the tricky part — we need to somehow have an append operation available on integers and strings. How? Well, in the eyes of our appendItems() method, they will not be integers and strings. They will be <em>something appendable</em>. It’s basically a case of <a href="https://en.wikipedia.org/wiki/Duck_typing">duck-typing</a>; if it walks like a duck and it quacks like a duck, as far as we’re concerned — it’s a duck. We don’t care what it really is, all we care about is that it’s able to quack. That’s what we’ll do here, just instead of our values being able to quack, we want them to be able to append.</p><p>Of course, the method above doesn’t compile since our generic type A has no method append(). So what do we do? I will explain two approaches to solving that problem — <em>implicit conversions</em> and <em>type classes</em>.</p><h4>Implicit conversions</h4><p>To assure the compiler that A will really be appendable, we can use an <em>implicit parameter</em>, a common mechanism in Scala, to provide a conversion:</p><pre>def appendItems[A](a: A, b: A)(implicit ev: A =&gt; Appendable[A]) =<br>  a append b</pre><p>This method says “I take two items of type A and I also need an implicit conversion from A to Appendable[A] to be available within scope”. We named this implicit conversion “ev” as short for “evidence”, which is one of many common terms for an implicit parameter in scenarios like this (another quite common one is “witness”).</p><p>We sort of “promised” the compiler that there will be a conversion from A to Appendable[A] available in scope when appendItems() is invoked. Compiler responds “OK, I will allow you to invoke append() on the value of type A because you promised that there will be an implicit conversion in scope and I’m counting on that”. If there isn’t one at compile time, compiler will be mad because we broke our promise and compilation will fail with an error saying “no implicit view available”. If you’re not familiar with where Scala searches for implicits, what’s the search scope and what gets precedence over what, I would highly recommend going through some materials on that (chapter 21 in <a href="http://booksites.artima.com/programming_in_scala_2ed">Programming in Scala</a> does a good job; you can also take a look in <a href="http://docs.scala-lang.org/tutorials/FAQ/finding-implicits.html">here</a>).</p><p>OK, we have the appendItems() method. Let’s move to the Appendable type.</p><p>First of all, Appendable is going to be a trait. It cannot be an ordinary class because append() needs to be abstract (it will be implemented separately for Integer and String). It could be an abstract class, but <a href="http://www.artima.com/pins1ed/traits.html#12.7">rule of thumb</a> is to prefer an abstract class only if there is a valid reason for that (e.g. we need to take some parameters in the constructor, some Java code will inherit it, efficiency is extremely important etc.).</p><p>Secondly, Appendable will be parameterized — it will have a type parameter. Why? Well, because its append() operation (not to be mixed up with our appendItems() method!) is generic; it is going to be <strong>implemented differently for different types, </strong>in our case as addition for integers and concatenation for strings. Since method append() is dependent of the type, the whole trait is dependent of the type. Note that if it weren’t dependent of the type then this would be a case of parametric polymorphism, but since it is, it’s a case of ad-hoc polymorphism.</p><p>So, here’s our nice little type-dependant trait:</p><pre>trait Appendable[A] {<br>  def append(a: A): A<br>}</pre><p>Now that we defined the trait let’s write those two different implementations of it, one for Integer and another one for String. Here they are:</p><pre>class AppendableInt(i: Int) extends Appendable[Int] { <br>  override def append(a: Int) = i + a<br>}</pre><pre>class AppendableString(s: String) extends Appendable[String] { <br>  override def append(a: String) = s.concat(a) <br>}</pre><p>Method <em>concat </em>is here for showcase purposes; I could have written simply (and more commonly)<em> s + other </em>which would concatenate them just as good, but I deliberately wanted it to differ from AppendableInt to emphasize that the implementation is specific for each type.</p><p>All that’s left to do now are the implicit conversions that we promised:</p><pre>implicit def toAppendable(i: Int) = new AppendableInt(i)<br>implicit def toAppendable(s: String) = new AppendableString(s)</pre><p>That was easy, wasn’t it? Now we can pass pure integers and strings to appendItems() and everything will type check. Here’s the full code that you can copy/paste and try out:</p><pre>trait Appendable[A] {<br>  def append(a: A): A<br>}<br><br>class AppendableInt(i: Int) extends Appendable[Int] {<br>  override def append(a: Int) = i + a<br>}<br><br>class AppendableString(s: String) extends Appendable[String] {<br>  override def append(a: String) = s.concat(a)<br>}<br><br>implicit def toAppendable(i: Int) = new AppendableInt(i)<br>implicit def toAppendable(s: String) = new AppendableString(s)<br><br>def appendItems[A](a: A, b: A)(implicit ev: A =&gt; Appendable[A]) = <br>  a append b<br><br>val res1 = appendItems(2, 3) // res1 is an Int with value 5<br>val res2 = appendItems(&quot;2&quot;, &quot;3&quot;) // res2 is a String with value &quot;23&quot;</pre><p>Quick recap of what we did: we have a method appendItems() that takes two items of type A and appends them using append(). Even though we expect A to be Int or String (which know nothing about append() method) everything will be fine because we provided implicit conversion as evidence. We “promised” the compiler that A will be convertible to Appendable. We keep our promise by defining two conversion methods called toAppendable, one from Int to Appendable[Int] and another one from String to Appendable[String]. Compiler is happy to see that we really did provide appendItems() with an implicit conversion so the whole thing works out perfectly and we are able to append our basic types Int and String with just one method even though they don’t extend any common trait.</p><h4>Type classes</h4><p>Implicit conversions were fun. Type classes are even more fun — they are more flexible and therefore more powerful. But instead of taking my word for it, read on and see for yourself.</p><p>Type classes are a concept originating from Haskell. Easiest way to describe them in terms of what we learned so far is that instead of <em>implicitly converting</em> to classes<em> </em>AppendableInt and AppendableString, we’ll make those<em> classes themselves </em>implicit. This means that we need to change our appendItems() method a little. It still takes two items to be appended, but instead of requiring an <em>implicit conversion</em>, it now requires an <em>implicit class instance</em>:</p><pre>def appendItems[A](a: A, b: A)(implicit ev: Appendable[A]) = <br>  a append b</pre><p>Unlike in Haskell, type classes are not an existing structure in Scala and they need to be modeled (similar to monads in my previous blog post). We usually do it by packing together a <strong>trait which defines the type class interface</strong> and<strong> implementations of that interface for various concrete types</strong>. Let me provide you with a two dozen lines of code which demonstrate that concept in its full glory:</p><pre>trait Appendable[A] {<br>  def append(a: A, b: A): A<br>}</pre><pre>object Appendable {<br>  implicit val appendableInt = new Appendable[Int] {<br>    override def append(a: Int, b: Int) = a + b<br>  }<br>  implicit val appendableString = new Appendable[String] {<br>    override def append(a: String, b: String) = a.concat(b)<br>  }<br>}</pre><pre>def appendItems[A](a: A, b: A)(implicit ev: Appendable[A]) =<br>  ev.append(a, b)</pre><pre>val res1 = appendItems(2, 3) // returns 5<br>val res2 = appendItems(&quot;2&quot;, &quot;3&quot;) // returns &quot;23&quot;</pre><p>See? We have a trait Appendable[A] and we have two instances of Appendable, one for Int and one for String.</p><p>One of the cool things about type classes is that it’s easy to extend libraries without touching existing code. For example, if you want to support some types other than Int and String, you just need to provide the implicit values for those types. You can import them from somewhere (just like we did in the first line of TypeClassTest) or define them yourself. This way you can not only provide implementations for some new types, but also override implementations for existing types, e.g. to append integers using multiplication instead of addition.</p><p>So when writing your own type class, it’s a nice convention to provide some initially supported default types in the type class companion object (it’s a convention, not a strict rule). Other users of your type class can then choose to use those default ones by importing the type class object or some other ones, either provided by someone else or themselves.</p><p>Here’s an example of overriding an implementation for an existing type, Int:</p><pre>trait Appendable[A] {<br>  def append(a: A, b: A): A<br>}<br><br>object Appendable {<br>  implicit val appendableInt = new Appendable[Int] {<br>    override def append(a: Int, b: Int) = a + b<br>  }<br>  implicit val appendableString = new Appendable[String] {<br>    override def append(a: String, b: String) = a.concat(b)<br>  }<br>}<br><br><strong>implicit val appendableInt2 = new Appendable[Int] {<br>  override def append(a: Int, b: Int) = a * b<br>}</strong><br><br>def appendItems[A](a: A, b: A)(implicit ev: Appendable[A]) =<br>  ev.append(a, b)<br><br>val <em>res1 </em>= <em>appendItems</em>(2, 3)<strong> // returns 6</strong></pre><p>Keep in mind that implicits are here to make your life easier. The whole thing could be done without them — for example, we could omit the “implicit” keyword from appendableInt2 and pass that object explicitly as <em>appendItems(2, 3)(appendableInt2)</em>. Using implicits makes things simpler, as long as you use them reasonably (having tons of implicits all around the place would be pretty messy and it would be hard to keep track of which exact implicit is being invoked at which place).</p><p>So, to summarize:</p><p>Type class is a concept of having a <strong>type-dependent interface</strong> and <strong>implicit</strong> <strong>implementations of that interface</strong>, with <strong>separate implementation for each supported type</strong>. In Scala the best way to model this is to use a parameterized trait and to put implicit implementations of that trait for supported types in the trait’s companion object (instead of implicit values you can also use implicit objects, but why pollute the namespace with extra types if you don’t have to). Type classes make it easy to add implementations for new types or to override implementations for existing types. Since these implementations are implicit, one must take into account precedence of implicits in Scala when reasoning about which one will be actually used.</p><h4>View and context bounds</h4><p>Ad-hoc polymorphism has been explained and implemented with two different approaches: implicit conversions and type classes. Now, there are two constructs in Scala, namely<em> view bounds</em> and <em>context bounds</em>, that provide some extra syntax sugar for working with those two approaches.</p><p>Let’s start from view bounds. Here’s how we could re-write our appendItems() method in implicit conversions scenario:</p><pre>// def appendItems[A](a: A, b: A)(implicit ev: A =&gt; Appendable[A]) = <br>//   a append b</pre><pre>def appendItems[A &lt;% Appendable[A]](a: A, b: A) = a append b</pre><p>See that [A &lt;% Appendable[A]]? That’s a view bound. It is interpreted as “method appendItems() is parameterized with A and it requires that there must be an implicit conversion from A to Appendable[A] available in scope”. This is the same behavior as before, just another syntax.</p><p>Now the context bound. Here’s how we could re-write our appendItems() method in type class scenario:</p><pre>// def appendItems[A](a: A, b: A)(implicit t: Appendable[A]) =<br>//   t.append(a, b)</pre><pre>def appendItems[A : Appendable](a: A, b: A) =<br>  implicitly[Appendable[A]].append(a, b)</pre><p>This time we parameterized with [A : Appendable], which is interpreted as “method foo() is parameterized with A and it requires that there must be an implicit value Appendable[A] available in scope”. Again, the same behavior as in the original type class example, just different syntax. Note that we have one extra bit of new syntax in the method body — the <em>implicitly</em> keyword. It is used to reference an instance of Appendable[A] that has been provided (since we no longer have “ev”).</p><p>Note that context bound construct is not strictly related to just type classes. It simply requires, given some type A, that an object or value of type Appendable[A] be implicitly available at point of invocation. It doesn’t care if we have some common parameterized trait or not. So, context bounds can come in handy when working with type classes, but you shouldn’t view them as type class syntax sugar; they’re a bit more general and not tied just to type class pattern.</p><h4>The big question — who wins?</h4><p>Actually, I already spoiled the answer to that question by mentioning that type classes provide us with more flexibility and power. If you payed enough attention, you may have even realized that yourself by now (hint: type class can have *multiple* implementations for the same type). But let’s back that up with a real world showcase.</p><p>Let’s say we want to sort the sequence of integers. We could use method <a href="http://www.scala-lang.org/api/current/index.html#scala.collection.Seq@sorted[B&gt;:A](implicitord:scala.math.Ordering[B]):Repr">sorted()</a> from Scala standard library:</p><pre>def sorted[B &gt;: A](implicit ord: math.Ordering[B]): Seq[A]</pre><p>Ordering is a type class; you can tell from the <a href="http://www.scala-lang.org/api/2.10.4/index.html#scala.math.Ordering">docs</a>:</p><blockquote>Ordering’s companion object defines many implicit objects to deal with subtypes of AnyVal (e.g. Int, Double), String, and others.</blockquote><p>See? Its companion object defines implicit objects to deal with various types, just like our Appendable object had implicit objects AppendableInt and AppendableString.</p><p>We learned by now what is sorted() trying to say with its signature. It says “when I’m invoked on a sequence of items of type A, I will sort that sequence, but in order to know how to compare items of type A there <em>needs to be an implicit Ordering in scope</em>”. By the way, note that Ordering needs to be parameterized with A or some supertype of A. This makes sense; if Integer is a Number, and I know how to sort Numbers, then I know how to sort Integers. But that’s beyond the point here, just wanted to clear that up.</p><p>Now, method sorted() didn’t always look like this. Ordering trait (we can also call it “type class Ordering”) is a new hipster kid on the block; before it, the streets belonged to the <a href="http://www.scala-lang.org/api/current/index.html#scala.math.Ordered">Ordered</a> trait. This was a plain, simple trait; your class extends it, implements its compare() method and it can be sorted. What’s wrong with that? Nothing, until you reach the point where you want to support more than one sorting criteria (e.g. you have strings containing only numbers and you want to be able to choose whether to sort them alphanumerically so that “11” comes before “2” or naturally so that “2” comes before “11”).</p><p>Type classes, as we discussed earlier, provide us with this kind of flexibility. So instead of having my class extend Ordered trait and provide just one hardcoded criteria for sorting, with Ordering trait it doesn’t have to extend anything. Instead, when I will be doing the sorting, I will provide an Ordering that suits my needs — I will import an alphanumerical ordering, a natural one or some third kind. Hell, maybe I’ll write my own and provide that. It even says so in the <a href="http://www.scala-lang.org/api/2.10.4/index.html#scala.math.Ordering">docs for Ordering</a> (bolding done by me):</p><blockquote>[Ordering] and scala.math.Ordered both provide this same functionality, but in different ways. A type T can be given a single way to order itself by extending Ordered. <strong>Using Ordering, this same type may be sorted in many other ways</strong>. Ordered and Ordering both provide implicits allowing them to be used interchangeably.</blockquote><p>So, type classes have demonstrated a greater flexibility, which also means greater power. As far as view bounds vs context bounds are concerned, things are even more clear —<strong> </strong><a href="https://github.com/scala/scala/pull/2909"><strong>view bounds have been deprecated</strong></a> and have therefore completely lost the fight<strong>. </strong>Martin Odersky himself <a href="https://groups.google.com/d/msg/scala-sips/wP6dL8nIAQs/plhN6pHKDmsJ">said</a>:</p><blockquote>Context bounds are essentially the replacement of view bounds. It’s what we should have done from the start, but we did not know better back then.”</blockquote><p>Poor view bounds. Implicit conversions are still in the game; sometimes you don’t really need type classes and using implicit conversions <a href="https://en.wikipedia.org/wiki/KISS_principle">makes things simpler</a>. View bounds, however, completely lost the fight against context bounds. The only reason why we were even talking about them is because they are still very much present in lots of existing codebases, so if you run into them you will know what’s going on.</p><h4>Conclusion</h4><p>As I said, you can still use implicit conversions for simple stuff. They’re fine for specific, non-modular, ad-hoc conversions. For example, if you have a standard MVC stack where controller uses services which operate on the database, you may want to automatically transform each database response into service response, and service response into controller response. No need for type classes there. However, when writing reusable, modular, generalized code that will be used and extended by others — gravitate towards type classes.</p><p>Regarding view and context bounds, if you want to follow the best practice, you should always prefer context bounds. If you really need to use the view bound, i.e. you want to make a method require that there is some implicit conversion, you can put that conversion in the implicit object and use the type class pattern with a context bound. Remember that this way you can provide different conversions, which gives you more flexibility.</p><p>As for the context bound syntax, using implicit parameter(s) instead (like we used “ev” in our example) is completely valid. Which style to prefer is a matter of personal taste and existing coding conventions in your team.</p><p>Just before we say goodbye, let me just state for the record that there are situations when type classes are just one of the possible solutions. For example, type classes are great if you want to have some generic code that works for many different types that <em>don’t share a common base class</em>. But if you have types that do share the same base class (e.g. Apple, Banana and Cherry all extend Fruit) then you can e.g. override Fruit’s common method in each fruit instance, so that apples bananas etc. all have different implementations of the same method. However, I have to be honest and say that I’m not a huge fan of subtyping so even in that case I would go for a type class. Subtyping doesn’t even exist in pure FP languages like Haskell. And in Scala it confuses the compiler in some situations and confuses the user in others. Just try having two classes Sub and Sup where Sub extends Sup, have a method that takes an implicit parameter of type Sup and have implicit values for both Sub and Sup available in scope; what do you think happens? Ambiguous implicit values error? Nope. Sup is used, since Sup is needed? Nope. What happens is that Sub is used, because compiler sees them as different enough to not have the ambiguousness, but equal enough to decide that not only is Sub actually a perfectly valid Sup, but it’s even the “better” one since it’s more specific. Now you see the problem with subtyping. Main rule of OOP inheritence is the “<em>is a</em>” rule, so Apple <em>is a</em> Fruit, but from the type system point of view it’s not. Type Apple is type Apple, type Fruit is type Fruit. This is the reason why extending case classes is deprecated (perhaps even not possible any more, I’d have to check). Because how do you treat <em>Apple(“red”) equals Fruit(“red”)</em>? True or false? OK I’m digressing too much, perhaps I should write a separate blog post on this topic. But yeah, whenever someone says you can simply use subtyping, feel free to say “I’d rather stick with true FP concepts”.</p><p>That’s it. Feel free to contact me at <em>sinisalouc@gmail.com </em>with any feedback you may have, good or bad, and also to follow me on <a href="https://twitter.com/sinisalouc">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=442ae22e5342" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying the Monad in Scala]]></title>
            <link>https://medium.com/free-code-camp/demystifying-the-monad-in-scala-cc716bb6f534?source=rss-690955769210------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc716bb6f534</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Sinisa Louc]]></dc:creator>
            <pubDate>Fri, 04 Dec 2015 21:50:48 GMT</pubDate>
            <atom:updated>2019-10-22T08:43:12.548Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CRR3Lql_Mk2aTO54G-JQxg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/sM3lniBo2LY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">davide ragusa</a> on <a href="https://unsplash.com/search/photos/mystical?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In my <a href="https://medium.com/@sinisalouc/variance-in-java-and-scala-63af925d21dc#.xvhs1zq7p">previous post</a> I mentioned how I decided to write about variance despite the fact that there are already several dozen articles about the topic. This is a similar situation. I am aware that this is a drop in the sea. I feel the sea is polluted with complex mathematical explanations involving category theory. Boring explanations which line up one definition after another without providing the gist of things.</p><p>I will not get technical, and by technical I mean mathematical. Stephen Hawking said that he was warned that every equation he put into “A brief history of time” (great book by the way) would halve the sales. I will go by the same principle here. But I will also try not to be too simplistic, and by simplistic I mean vague. We do need to get our hands dirty. Last, but not least, I will provide examples as a primary mean of explaining. Examples are more as a supplement to the main explanation.</p><h4>Introduction</h4><p>So, what is a monad?</p><p>You can think of monads as <strong>wrappers</strong>. You just take an object and wrap it with a monad. It’s like wrapping a present; you take a scarf, a good book or a fancy watch, and wrap it with some shiny paper and a red ribbon. We wrap gifts with shiny paper because they look pretty. We wrap objects with monads because monads provide us with the following two operations:</p><ul><li><strong>identity</strong> (<em>return</em> in Haskell, <em>unit</em> in Scala)</li><li><strong>bind</strong> (<em>&gt;&gt;=</em> in Haskell, <em>flatMap</em> in Scala)</li></ul><p>Scala doesn’t come with a built-in monad type like Haskell so we will model the monad ourselves. If you take a look at some cool functional programming libraries like <a href="https://github.com/scalaz/scalaz">Scalaz</a> you will find monads there. You will also find the rest of the category theory family (functors, applicatives, monoids and so on). In plain Scala, there’s no such thing out of the box.</p><p>We will model a monad with a generic trait that provides methods unit() and flatMap(). We can call it M instead of Monad simply to be more concise. Here it is:</p><pre>trait M[A] {<br>  def flatMap[B](f: A =&gt; M[B]): M[B]<br>}<br>  <br>def unit[A](x: A): M[A]</pre><p>See, it provides two aforementioned functions, <em>unit</em> and <em>flatMap</em>. Don’t worry about their signatures, what they do for now or why the unit() method is outside the trait body. We’ll get to that in a moment.</p><p>Now, note one very important thing here — there is a <strong>concept of monad </strong>(which we modeled in Scala half a minute ago). There are <strong>concrete monads</strong> of flesh and blood which implement those two functions and actually do something (e.g. IO monad). Sometimes people refer to one thing and sometimes the other, so be careful. We will encounter a couple of concrete monads later in this article. You can think of a generic monad as an interface and concrete monads as implementations.</p><p>There’s one more thing you should pay attention to — monads take a type parameter. We didn’t just write M; we wrote M[A]. The type parameter is like a label sticker on our gift wrap, saying what kind of object we have inside (in real life this would ruin the surprise, but in programming, we don’t like surprises). So if we want to wrap some object with our monad wrapper, we must parameterize the monad with the type of the underlying object, e.g. M[Int], M[String], M[MyClass] etc.</p><p>Now let’s take a closer look at those two functions.</p><h4>Monad functions</h4><p>In case you just joined us, let me repeat that monads come with two operations, <em>unit</em> (also known as <em>identity</em> or <em>return</em>) and <em>flatMap</em> (also known as <em>bind</em>). By the way, literature and online sources are rich with all kinds of naming. I merely mentioned the most common ones. Wait, I forgot one — unit is also often called <em>pure</em>. But don’t worry, it’s always pretty straightforward which function is being referred to, no matter which naming is used. Oh, they also use <em>zero</em> for unit sometimes. All right, let’s move on.</p><p>Unit performs the wrapping part. So, in case of our gift wrap analogy, we can pass a book to unit(). It will return our book wrapped up in this super cool shiny colorful wrap paper, with a “book” label on it. And in case of our monad trait, if we give it a value of type A, it will return a value of type M[A]. It’s sort of a monad constructor, if you will.</p><p>It should become clear at this point why we defined the method unit() outside the trait body. Because we don’t want to invoke it upon the existing monadic object (e.g. myMonad.unit(“myBook”)). That wouldn’t make much sense. We want it as a standalone static method (e.g. unit(“myBook”)). By passing our book to unit(), we get it back wrapped in a monad.</p><p>Now, about the flatMap. You may already be familiar with it; it’s the very same flatMap you can encounter in other places in Scala, such as collections. Here’s its signature:</p><pre>def flatMap[B](f: (A) =&gt; U[B]): U[B]</pre><p>Let’s say U is a List. It works for various other types, but we’ll use List for this example. Now, what flatMap does is that it takes a function with signature A <em>→ </em>List[B] and it uses that function to transform the underlying object of type A into a List[B]. This operation is known as <em>map</em>. Since we transformed our underlying A into a List[B], this leaves us with a List[List[B]]. But we did not use ordinary map() — we used flatMap(). This means that the job is not done yet; flatMap will now “flatten” our List[List[B]] into List[B].</p><p>Let’s look at a concrete example. If A is Int, and our function <em>f</em> is</p><pre>val f = (i: Int) =&gt; List(i - 1, i, i + 1)</pre><p>then we can flatMap a list of integers with <em>f</em> as follows:</p><pre>val list = List(5, 6, 7)<br>println(list.flatMap(f))<br>// prints List(4, 5, 6, 5, 6, 7, 6, 7, 8)</pre><p>Note that regular map() would take each number <em>i</em> and expand it to a mini-list <em>(predecessor, original number, successor)</em> which would give us the following list of mini-lists: List((4, 5, 6), (5, 6, 7), (6, 7, 8)). FlatMap goes one step further; it flattens that into one long list, resulting in<br>List(4, 5, 6, 5, 6, 7, 6, 7, 8).</p><p>Now let’s say that we have some class M with an underlying type A, written as M[A]. If we want to <a href="http://1.bp.blogspot.com/-f5T38j9evCk/VZ54cIBwUeI/AAAAAAAABLY/3bvMZaQ4HCY/s640/nzfiq.jpg">flatMap that sh*t</a> (I didn’t invent this phrase; try Googling it) we need to provide a function A <em>→ </em>M[B]. FlatMap will then use this function to transform our underlying A into M[B], resulting in a M[M[B]], and then it will flatten the whole thing into M[B].</p><pre>         map with A =&gt; M[B]                  flatten<br>M[A]  -------------------------&gt;  M[M[B]]  -----------&gt; M[B]</pre><p>Notice how flatMap doesn’t require a function A <em>→ </em>M[A], but a more flexible one, A <em>→ </em>M[B]. So if M is a List and A is an Int, we can feed the flatMap with functions such as Int <em>→ </em>List[String], Int <em>→ </em>List[MyClass] and so on. It doesn’t have to be Int <em>→ </em>List[Int]. For example, we could have defined <em>f</em> as:</p><pre>val f = (i: Int) =&gt; List(&quot;pred=&quot; + (i - 1), &quot;succ=&quot; + (i + 1))</pre><p>and then we could flatMap a list of integers with it like this:</p><pre>val list = List(5, 6, 7)<br>println(list.flatMap(f))<br>// prints List(pred=4, succ=6, pred=5, succ=7, pred=6, succ=8)</pre><p>FlatMap is way more powerful than map. It gives us the ability to chain operations together, as you’ll see in the examples section. Map functionality is just a subset of flatMap functionality. If you want to have map() available in your monad, you can express it using monad’s existing methods flatMap() and unit() like this (note that <em>g</em> is some function <em>Int → Something</em>, not <em>Int → List[Something]</em>):</p><pre>  m map g = m flatMap (x =&gt; unit(g(x)))</pre><p>If all we had was map and unit, we would not be able to define flatMap because neither one of them has a clue about flattening. Flatten (also known as <em>join</em> in Haskell) is a very important part of the process in our monad machine. If we had a map, but no ability to flatten (and therefore no flatMap), then we would end up with what is known in category theory as <em>functor</em>. Functors are pretty cool too, but monads are the star of our show so let’s not digress.</p><p>By the way, if we decompose <em>flatMap</em> into <em>map</em> (<em>fmap</em>) and <em>flatten</em> (<em>join</em>) we will create a <a href="https://en.wikipedia.org/wiki/Monad_%28functional_programming%29#fmap_and_join">completely equivalent</a> and valid definition of the monad. That definition would then look something like this:</p><ul><li>def unit: A → F[A]</li><li>def map: F[A] → (A → B) → F[B]</li><li>def flatten: F[F[A]] → F[A]</li></ul><p>Note that I wrote <em>map’s</em> signature as a fully standalone, “neutral” function here. Meaning that it’s defined without any additional context instead of as a method on F[A].</p><p>Such <em>map</em> first takes an instance of F[A] first (say, List(42)), then a function A → B (such as a → a + 1) and then gives us back an instance of F[B] (in our case List(43)). I wrote it that way only to be able to write the corresponding <em>flatten</em> signature as well. If I had written map simply as A → B, assuming that it’s defined as a method on F[A], then I would have had a hard time writing down the signature for <em>flatten. </em>It would have to be a function Unit → F[A], defined only on instances of F[F[A]], which makes things clunky. By writing down the “neutral” signatures things should be clear.</p><p>Anyways, we will stick to the flatMap version, and we will continue to view <em>map’s</em> signature as A → B instead of F[A] → A → B, meaning that F[A] is already known at the time of invocation (it’s the instance upon which we’re invoking the method map()).</p><h4>Exposing the monad</h4><p>As I said earlier, there is no such thing as monad type class in Scala. But<em> that doesn’t mean there are no monads in Scala</em>. Monad is not a class or a trait; monad is a concept. Every “wrapper” that provides us with our two beloved operations, <em>unit, </em>and <em>flatMap</em>, is essentially a monad (well, it’s not really enough to just provide methods with those names, they, of course, have to follow certain laws, but we’ll get to that).</p><p>I think we can now finally put the two and two together and realize that<strong> List is a monad</strong>! Let that sink in. What a plot twist, huh? It’s like in that movie when you realize that it was *him* all along. But wait — there are others! Set? Monad. Option? Monad. Future? Monad!(*)</p><p>OK, it’s a mass conspiracy movie. Monads are everywhere!</p><p><em>(*): There is a slight controversy whether Future really is or isn’t a monad. Since this is a beginners-friendly text, I will just say that it is a monad and call it a day.</em></p><p><em>In case someone from the Future-is-not-a-true-monad camp is reading this, I’m sure you’ll agree that this is not the place for that debate. Perhaps I’ll even write an article on that too someday.</em></p><p><em>I agree that their breaking of some fundamental functional programming principles such as referential transparency should not go unnoticed. But let’s leave that for some other time.</em></p><p>When you look at them up close, you can see that each one indeed has a flatMap method. What about unit? Well, remember that unit is an operation that creates a monad M[A] from an object of type A. This means that a simple apply() serves as a perfectly good unit. So if we have an object called x, here’s what unit operation looks like in various monads (recall that there’s syntax sugar that allows us to invoke e.g. List.apply(3) as List(3)):</p><pre>List:          Set:          Option:                 Future:<br>------------------------------------------------------------------<br>List(x)        Set(x)        Some(x) or Option(x)    Future(x)</pre><p>Also, as I said earlier, there is no actual monad type class in plain Scala. Constructs such as List, Option, Future etc. don’t extend any special Monad trait (it doesn’t exist). This means that they are not obligated to provide us with methods called <em>unit</em> and <em>flatMap</em>. It’s by observing them and seeing that they have methods unit() and flatMap() with correct signatures and behavior that we can deduct that they are, in fact, monads.</p><p>I can hear you say “but if there’s no actual unit() method in Scala (since we said that apply() in monad’s companion object serves as unit), what did you mean by saying “<em>return</em> in Haskell, <em>unit</em> in Scala? What, <em>unit</em> is a name for a function that doesn’t exist?”</p><p>That’s a good observation, and yes, you are quite right. “Unit” is merely a convention for referencing monad’s identity operation in Scala. You can create a perfectly good custom monad and call its methods <em>galvanize</em> and <em>dropTheBass</em> instead of <em>unit</em> and <em>flatMap</em> if you wish. As long as they have proper signatures and do what they’re supposed to, it will conceptually be a monad. But convention is a nice thing, and Scala community embraced the terms <em>flatMap</em> (as seen in List, Option, Future) for the bind operation and <em>unit</em> (by convention implemented as apply()) for the identity operation.</p><p>I said, “as long as they have proper signatures and do what they’re supposed to”. OK, we covered the signatures part, but we never really specified what it is exactly that these methods have to do. I mean, we <em>discussed</em> how they should behave, but this is not really enough to define their requirements in more concrete terms. This is where<strong> monad laws</strong> come into play. These laws must be obeyed by <em>unit</em> and <em>flatMap</em> if our monad is to indeed be a true, proper monad.</p><p>Since this is a beginner-friendly text, I will not go into too much details about the theory behind the laws or even demonstrating their correctness. For now it’s important that you know that they exist. It’s OK if you postpone working through them until you get some practice.</p><p>So, if we have some basic value <em>x</em>, a monad instance <em>m</em> (holding some value) and functions <em>f</em> and <em>g </em>of type <em>Int → M[Int]</em>, we can write the laws as follows:</p><ul><li><strong>left-identity law</strong>: <br><em>unit(x).flatMap(f) == f(x)</em></li><li><strong>right-identity law</strong>: <br><em>m.flatMap(unit) == m</em></li><li><strong>associativity law</strong>:<br><em>m.flatMap(f).flatMap(g) == m.flatMap(x ⇒ f(x).flatMap(g))</em></li></ul><p>Alright. So far we have achieved two out of three goals that I aimed for in this article. We explained the concept of a monad and we drew a parallel to some real-life monads in Scala. By the way, in the beginning I only mentioned IO-monad as an example of a concrete monad. I wanted to postpone mentioning the others until you had an idea about the general concept.</p><p>In case you’re wondering what the hell is an IO-monad anyway, it’s a quite complex little thingy used for IO operations in purely functional languages such as Haskell. This is not the time or place to dive deeper into that one.</p><p>Time for the third goal — why are monads useful?</p><h4>Monads in practice: Option</h4><p>In this section, I will show two monads, Option, and Future.</p><p>We’re starting with Option. As you probably know, Option is a construct that allows us to avoid null pointers in Scala (in Haskell it’s called Maybe). We use it for things that may or may not have a defined value. If a value is defined, option equals Some(value), and if it’s not defined, it equals None.</p><p>Let’s say we have a bunch of users stored in some database. We also have a service that can load a user from that database with a method loadUser(). It takes a name and provides us with an Option[User] because user with that name may or may not exist.</p><p>Each user may or may not have a child (for the sake of the example let’s say there’s a law enforced in the state which allows a maximum of one child). Note that the child is also of type User, so it can have a child too.</p><p>Last, but not least — we have a simple function <em>getChild </em>which returns the child for a given user.</p><pre>trait User {<br>  val child: Option[User]<br>}</pre><pre>object UserService {<br>  def loadUser(name: String): Option[User] = { /** get user **/ }<br>}</pre><pre>val getChild = (user: User) =&gt; user.child</pre><p>Now let’s say we want to load a user from the database and if they exist we want to see if they have a grandchild. We need to invoke these three functions:</p><p>String <em>→ </em>Option[User] // load from db<br>User <em>→ </em>Option[User] // get child<br>User <em>→ </em>Option[User] // get child’s child</p><p>And here’s the code.</p><pre>val result = UserService.loadUser(&quot;mike&quot;)<br>  .flatMap(getChild)<br>  .flatMap(getChild)</pre><p>If you didn’t know how to flatMap a monad, you would probably wind up writing a couple of nested if-then-else branches, checking if option is defined. Nothing wrong with that, but this is far more elegant, concise and in the spirit of functional programming.</p><p>OK, let’s take a closer look at our “optional user” monad. Remember what we learned earlier. Here’s the analogy.</p><pre>generic monad:<br>--------------<br>unit:     A =&gt; M[A]           <br>flatMap: (A =&gt; M[B]) =&gt; M[B]  </pre><pre>our monad:<br>-------------- <br>unit:     User =&gt; Option[User]<br>flatMap: (User =&gt; Option[User]) =&gt; Option[User]</pre><p>By the way, you can also write those functions as in-place lambda functions instead of defining them a priori. Then the code becomes this:</p><pre>val result = UserService.loadUser(&quot;mike&quot;)<br>  .flatMap(user =&gt; user.child)<br>  .flatMap(user =&gt; user.child)</pre><p>or even more concise:</p><pre>val result = UserService.loadUser(&quot;mike&quot;)<br>  .flatMap(_.child)<br>  .flatMap(_.child)</pre><p>You can also use a for-comprehension which is basically syntax sugar for mapping, flatMapping, and filtering. I don’t want to digress too much so I won’t explain it here, you can look it up; I’ll just show you the code.</p><pre>val result = for {<br>  user             &lt;- UserService.loadUser(&quot;mike)<br>  usersChild       &lt;- user.child<br>  usersGrandChild  &lt;- usersChild.child<br>} yield usersGrandChild</pre><p>If you find all this a bit confusing, fiddling around with your own code helps a lot. You can create some dummy users, add a basic implementation to UserService.loadUser() so that it return one of them. Make them raise a ton of children and grandchildren and flatMap the living daylights out of them.</p><h4>Monads in practice: Future</h4><p>Future is a wrapper over some asynchronous operation. Once the future has been completed you can do whatever it is you need to do with its result.</p><p>There are two main ways to use a future:</p><ul><li>use future.onComplete() to define a callback that will work with the result of the future (not so cool)</li><li>use future.flatMap() to simply say which operations should be performed on the result once future is complete (cleaner and more powerful since you can return the result of the last operation)</li></ul><p>On to our example. We have an online store and customers who have placed thousands of orders. For each customer, we must now get his/her order, check which item the order is for, get the corresponding item from the database, make the actual purchase and write the result of purchase operation to log. Let’s see that in code.</p><pre>// needed for Futures to work<br>import scala.concurrent.Future<br>import scala.concurrent.ExecutionContext.Implicits.global</pre><pre>trait Order<br>trait Item<br>trait PurchaseResult<br>trait<strong> </strong>LogResult</pre><pre>object OrderService {  <br>  def loadOrder(username: String): Future[Order] <br>}<br>object ItemService {  <br>  def loadItem(order: Order): Future[Item] <br>}<br>object PurchasingService { <br>  def purchaseItem(item: Item): Future[PurchaseResult]<br>  def logPurchase(purchaseResult: PurchaseResult): Future[LogResult] <br>}</pre><p>By the way, don’t mind stuff like referencing global objects from within functions. I know it’s not best practice. But that is completely beside the point here. Also, note that code above doesn’t compile because I left out the implementations of service methods for clarity. Again, if you want to play with the example yourself (and I recommend it), you can create mock implementations yourself. e.g. def loadItem(order: Order) = Future(new Item{}).</p><p>Now, similarly to the Option example, there are a couple of functions that we will use. They’re pretty trivial as each one simply invokes a method from the corresponding service.</p><pre>val loadItem: Order =&gt; Future[Item] = {<br>  order =&gt; ItemService.loadItem(order)<br>}</pre><pre>val purchaseItem: Item =&gt; Future[PurchaseResult] = {<br>  item =&gt; PurchasingService.purchaseItem(item)<br>}<br><br>val logPurchase: PurchaseResult =&gt; Future[LogResult] = {<br>  purchaseResult =&gt; PurchasingService.logPurchase(purchaseResult)<br>}</pre><p>We need to load the order for a given customer, get the item in question, make the purchase of that item and log the result. It’s as easy as:</p><pre>val result = <br>  OrderService.loadOrder(&quot;customerUsername&quot;)<br>  .flatMap(loadItem)<br>  .flatMap(purchaseItem)<br>  .flatMap(logPurchase)</pre><p>Here’s the equally nice for-comprehension alternative, using direct service method invocations instead of the functions that were used above:</p><pre>val result =<br>  for {<br>    loadedOrder    &lt;- orderService.loadOrder(“customerUsername”)<br>    loadedItem     &lt;- itemService.loadItem(loadedOrder)<br>    purchaseResult &lt;- purchasingService.purchaseItem(loadedItem)<br>    logResult      &lt;- purchasingService.logPurchase(purchaseResult)<br>  } yield logResult</pre><p>That’s it. I hope I managed to shed some light on the mystery of monads.</p><h4>Conclusion</h4><p>Monad with his two weapons, unit and flatMap, is a pretty powerful guy. Of course, they are not the solution to <em>all</em> your problems. But thinking in this way (chaining operations and manipulating data using map, flatMap, filter etc., accompanied by other functional programming constructs such as pattern matching) really improves your reasoning about the code and lowers the number of bugs in it.</p><p>And given the fact that code is much more often read than written, readability and clearness of such code is a big plus. For example, here’s an excerpt from the code I wrote at work today (I changed the names):</p><pre>itemService.loadItems(order).flatMap {</pre><pre>  case Success(items) =&gt;<br>    val updateResults = items.map { item =&gt;<br>      itemService.purchase(item, order.owner)<br>    }<br>    Future.sequence(updateResults)<br>      .map(toPurchaseResults(_))<br>      .map(mergeResults(_))</pre><pre>  case RepositoryFailure(failure) =&gt;<br>    Future(Failure(Json.obj(Failed -&gt; FailureLoadingItems)))</pre><pre>}</pre><p>Forget entangled if-branches, nested loops with their off-by-one errors and <a href="http://callbackhell.com/">callback hell</a>. This code is simpler, prettier and, with a little help from the Scala compiler, <em>works the first time you run it</em>.</p><p>You can catch a glimpse of some other category theory constructs <a href="http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html">here</a> or go for a more detailed reading <a href="http://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/">here</a>.</p><p>Regarding functional programming in general, if you like Scala you could start from <a href="https://www.manning.com/books/functional-programming-in-scala">here</a>.</p><p>There are also some nice libraries that provide functional programming constructs, such as <a href="https://github.com/scalaz/scalaz">Scalaz</a> (which was already mentioned earlier) and <a href="https://github.com/non/cats">Cats</a> (younger kid on the block) so try playing around with them; you can find some tutorials <a href="http://eed3si9n.com/">here</a>.</p><p>And if you want to get seriously involved with functional programming, you will have to <a href="http://learnyouahaskell.com/chapters">learn Haskell</a> sooner or later (in case you don’t already know it).</p><p>Here’s my email: sinisalouc[at]gmail[dot]com. If you find any mistakes, think that some specific part needs improvement or simply want to get in touch, feel free to contact me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc716bb6f534" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/demystifying-the-monad-in-scala-cc716bb6f534">Demystifying the Monad in Scala</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Variance in Java and Scala]]></title>
            <link>https://medium.com/javarevisited/variance-in-java-and-scala-63af925d21dc?source=rss-690955769210------2</link>
            <guid isPermaLink="false">https://medium.com/p/63af925d21dc</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sinisa Louc]]></dc:creator>
            <pubDate>Sun, 22 Nov 2015 17:14:19 GMT</pubDate>
            <atom:updated>2024-03-23T05:34:56.736Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Complete Guide to Variance in Java and Scala</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIvRsp2QvkBG-FijXpl-QA.png" /></figure><p>This text aims to explain variance in type parameters both in Java and Scala. There is already a lot of material on this subject in various blogs and articles, but to me, they always felt either too complex, diving straight into advanced features and is hard to follow for someone new to the topic, or too simplistic and merely scratching the surface.</p><p>So, here’s my attempt at filling that gap.</p><h4>First, a little background</h4><p>I assume most (or all) of you are well acquainted with the concept of polymorphism in object-oriented programming. It’s cool to be able to e.g. test if an array is equal to another array, but without implementing the equality method for each and every type of <a href="https://javarevisited.blogspot.com/2012/01/sort-array-in-java-ascending-and.html#axzz5XfRjTLwH">array</a>.</p><p>We just want to use the <a href="https://javarevisited.blogspot.com/2011/02/how-to-write-equals-method-in-java.html">equals() method </a>(assuming it’s defined for every object, which is true for <a href="https://medium.com/javarevisited/10-best-places-to-learn-java-online-for-free-ce5e713ab5b2">Java </a>and <a href="https://medium.com/javarevisited/10-best-scala-and-functional-programming-online-courses-for-beginners-b6461b27bf">Scala</a>) and we don’t want to care which exact type of object is actually contained in an array.</p><p>In Java, Integer[] is a subclass of Number[], and they are both subclasses of Object[]. This is called <strong>covariance</strong>. Given A &lt;: B (meaning A is a subclass of B), if T[A] &lt;: T[B] then T is covariant in its type. Given the same relationship A &lt;: B, if T[B] &lt;: T[A] then T is <strong>contravariant</strong> in its type.</p><p>If this is the first time you heard about contravariance it probably doesn’t make much sense to you right now, but wait until the end of this article. Finally, if T[A] and T[B] have no relationship despite the fact that A &lt;: B, then we say T is <strong>invariant</strong> in its type.</p><blockquote>By the way, if you looking for resources to learn Scala then I suggest you check out<strong> the</strong><a href="https://medium.com/javarevisited/10-best-scala-and-functional-programming-online-courses-for-beginners-b6461b27bf"><strong> Scala and Functional Programming for Beginners | Rock the JVM</strong></a> course on Udemy to start with. It’s a nice course for beginners who are both new to Scala and Functional programming.</blockquote><p><a href="https://medium.com/javarevisited/10-best-scala-and-functional-programming-online-courses-for-beginners-b6461b27bf">10 Best Scala Courses and Tutorials to Learn Functional Programming in 2024</a></p><p>So, arrays are covariant in Java. We can have a method isEqual() or sort() or shuffle() that takes an array of objects and we can pass in whatever array we want. Yay! We can also define a method taking an array of e.g. geometric shapes and pass in array of GeometricShapes, or Triangles, or EquilateralTriangles, and so on. Polymorphism at its finest.</p><p>Well, it comes at a price. Let’s say we have an array of integers. This is a subclass of an array of objects, right? So if I have a variable called “objectArray” that is an array of objects, it’s perfectly valid to assign our array of integers to objectArray.</p><p>Now we have a variable objectArray that is seen by the compiler as an array of objects, but underneath what we <em>really</em> have is an array of integers. OK, this is not a big problem… yet. But, our array of integers is now an array of objects in the eyes of the compiler! We are allowed to store strings and triangles and bananas — the compiler will just stand there and allow it to happen. Of course, at runtime our code will crash and burn when we get stuff from the original variable holding an array of integers (or, more precisely, variable which *thinks* it’s still holding an array of integers while in reality it’s holding all kinds of stuff).</p><p>We have encountered a problem. But what to do? There’s no turning back now (we’re talking 2004) because there are already thousands and thousands of commercial projects around the world using Java. Arrays will have to remain “hackable”. But, there was this cool new thing called <em>generics</em> coming up in Java 5. As you probably already know, they are written inside &lt;&gt; in Java, while <a href="https://medium.com/javarevisited/7-free-scala-and-functional-programming-courses-for-beginners-370f3cd41a4e">Scala </a>uses [] notation. Generics allow any class to have a type tag just like an array does, but unlike arrays, these type tags are <strong>not covariant</strong>.</p><p>So, in Java, MyClass&lt;String&gt; is not a subclass of MyClass&lt;Object&gt;. That’s great, generics can’t crash and burn! But yes, that means we don’t have that neat little polymorphism feature that we had with arrays. Method that takes MyClass&lt;Object&gt; cannot be passed an instance of MyClass&lt;String&gt;. We also can’t pass a List of Strings where List of Objects is needed. That’s a shame. We can always force some ugly casting, but that can be dangerous in the runtime (bringing us back to what we hated about arrays) and is considered a big no-no.</p><h4>Bounds to the rescue</h4><p>There is a way to achieve polymorphism (that is, covariance and contravariance) in this situation — by using <strong>bounded wildcards. </strong>There are two types of bounds for wildcards — upper bounds and lower bounds. Upper bound allows one to restrict the type “from above”, that is, to specify what’s the highest level of hierarchy allowed, while lower bound restricts the type “from below” by specifying what’s the lowest type that’s allowed. Here’s an example of an upper bounded wildcard:</p><pre>public void process(List<strong>&lt;? extends Car&gt;</strong> list) { ... }</pre><p>This means that process() accepts List parameterized by Car or <em>any subclass </em>of Car. Yay, covariance! And if we switch extends with super, it becomes a lower bound:</p><pre>public void process(List<strong>&lt;? super Car&gt;</strong> list) { ... }</pre><p>Now process() only accepts Lists parameterized by Car or <em>any superclass</em> of Car, thus achieving contravariance.</p><p>Good. We have the polymorphism we wanted. We have a method process() whose argument can be covariant or contravariant in its type, depending on whether we use upper or lower bounded wildcard. Note that bounds in Java are not just available for wildcards, but also for<em> type parameters</em>, so we can declare a class such as MyClass&lt;T extends Car&gt;. Type parameter (such as T) is different from wildcard (denoted by ?) in sense that it can be reused in the rest of the code. There are two major differences in bounded type parameters compared to bounded wildcards:</p><ul><li>With type parameters you can specify <strong>more than one bound</strong>. But since in Java you can only extend one superclass, other bounds specify the interfaces that must be implemented. For example, MyClass&lt;T extends Bird &amp; CanSwim &amp; CanRun&gt; means that type parameter for an instance of MyClass must extend Bird and implement CanSwim and CanRun.</li><li><strong>Only upper bounds</strong> can be used for type parameters. This means that MyClass&lt;T extends Bird&gt; is OK, but MyClass&lt;T super Bird&gt; won’t compile. Reasons for that are beyond the scope of this (already lengthy enough as it is) article, but we won’t be using bounds on type parameters anyway so I guess that’s OK. Let me just add that in Scala you can have both upper and lower bounds on type parameters, written as [T &lt;: Bird] and [T &gt;: Bird] respectively.</li></ul><p>Let’s get back to bounds on wildcards since they do provide us with both covariance and contravariance. We achieved polymorphism and are able to provide our process() method with subtypes or supertypes of List&lt;Car&gt;, depending on whether we declared the list parameter as covariant (using upper bound) or contravariant (using lower bound). Now, there are some important limitations when using bounded wildcards that must be considered: we can only get stuff from the covariant list, and we can only put stuff in the contravariant list. Actual rule is a bit more general since the parameterized class could be anything, not just a List-like container. It goes like this: we can only use the <strong>covariant type parameter as a return type</strong>, and we can only use the <strong>contravariant type parameter as an input type</strong>. Let’s explain this on the List get-put example.</p><p>In case of covariant List&lt;? extends Car&gt; (also known as upper bounded list), we know that there are instances of Car inside. Some are sports cars, some are limos, maybe we also have further subclasses (e.g. AstonMartin), but they’re all cars. We can get objects from that list and know that what we’re getting is a Car. However, since we don’t know what the actual underlying type is (Car or SportsCar or AstonMartin), if such a list were to allow stuff to be put inside, then we would have the same problem as with arrays. We could create a list of sports cars, safely assign it to a List&lt;Car&gt; variable and then “safely” (as far as compiler is concerned) put limos inside. At runtime we would crash and burn again. The only thing we are allowed to put is null because it extends everything so whatever the actual underlying type is — null extends it.</p><p>On the other hand, in case of contravariant List&lt;? super Car&gt; (also known as lower bounded list), we know that it’s safe to put cars inside (this includes subtypes such as AstonMartin; they are also cars). Whatever the actual underlying type may be (e.g. a Vehicle or AnyRef), every Car extends it, so if we put an AstonMartin when actual underlying type is a Vehicle — we did nothing wrong, did we? AstonMartin is a Vehicle. But the situation is now opposite than with the upper bound — while we can put cars, we can’t get anything from this list (actually, we can, but it will be of type Object which is not very useful). We can’t get a Car because if the underlying type is, say, a Vehicle, then we would be in trouble. We don’t know what the actual underlying type is — for all we know, List could also be full of motorcycles, tractors and amphibious ATVs. Getting an object of type Car from that list could potentially cause a runtime exception.</p><p>Here’s all that in code:</p><pre>List&lt;? extends Integer&gt; a = new ArrayList&lt;Integer&gt;();<br>List&lt;? super Integer&gt; b = new ArrayList&lt;Integer&gt;();</pre><pre>a.add(3);    // fails; let’s try with null<br>a.add(null); // works<br>b.add(3);    // no problem here</pre><pre>Integer ai = a.get(0); // no problem here either<br>Integer bi = b.get(0); // fails; let’s try with Object<br>Object o = b.get(0);   // works</pre><p>You can also think of it this way: in both cases, you can only put lowest (most specific) allowed type and you can only get highest (most general) allowed type. For covariant (upper bounded) lists, the lowest allowed type is null and highest is Car, whereas for contravariant (lower bounded) lists lowest allowed type is Car and highest is Object</p><pre>                upper bound            lower bound<br>       null ------------------- Car ------------------- Object</pre><p>OK, so we can only get stuff from a covariant list and we can only put stuff into a contravariant list. This is called a <em>get-put principle</em>. Now let’s go back to the more general rule:</p><ul><li>use <strong>covariance</strong> for methods which <strong>return</strong> a generic type</li><li>use <strong>contravariance</strong> for methods which <strong>take</strong> a generic type</li><li>use <strong>invariance</strong> for methods which <strong>both</strong> accept and return a generic type</li></ul><p>Quick recap: Arrays in Java are <a href="https://javarevisited.blogspot.com/2014/03/covariant-method-overriding-of-java-5.html">covariant</a>, which allows dirty stuff that makes our code crash and burns. Generic (we can also call them parameterized) classes are invariant, which makes them immune to crashing and burning, but we lose polymorphism. We can achieve covariance and contravariance (and bring back the polymorphism) for each method through the usage of wildcard bounds, but when defining variance for a method we must keep the get-put principle in mind.</p><h4>What about Scala?</h4><p>First of all, in Scala, arrays are <strong>invariant</strong>, which removes the possibility of crashing and burning. As for lists, they are now <strong>covariant by default</strong>. They are safe to be covariant due to their immutability; there’s no danger of someone assigning a list of integers to a list of objects (since immutability disallows re-assignment; instead, every “add” operation on a List returns a new List). Immutability saved us from the ugly dilemma between losing polymorphism and crash-and-burn scenarios.</p><p>But let’s be honest here — this is not a major improvement. Arrays simply went for the lesser evil (instead of being prone to crash-and-burn, they now have no polymorphism), and lists became covariant just because they are immutable by default. One can also use <a href="https://javarevisited.blogspot.com/2018/02/java-9-example-factory-methods-for-collections-immutable-list-set-map.html">immutable lists in Java</a> (such as ImmutableList in Guava library) or implement their own, and go for covariance using upper bounds.</p><p>Real improvement is in the language itself. Java only supports <strong>use-site variance,</strong> which means that variance is defined when the type parameter is <em>used.</em> In practice this means that it is defined separately for each method using bounded wildcards.</p><p>Scala, on the other hand, supports both use-site variance (syntax is similar to Java, just replace &lt;? extends T&gt; with [_ &lt;: T]) and <strong>declaration-site variance. </strong>Declaration-site, as the name suggests, means that variance is defined when the type parameter is <em>declared</em>. You can simply declare covariance by putting “+” in front of the type parameter, and “-” for contravariance (no sign means invariance).</p><p>So, in Java you would say:</p><pre>public class Foo&lt;T&gt; { ... }<br>...<br>Foo&lt;? extends Integer&gt; covariantFoo = new Foo&lt;Integer&gt;();<br>Foo&lt;? super Integer&gt; contravariantFoo = new Foo&lt;Integer&gt;();</pre><p>Notice how Foo appears to be covariant in one case (covariantFoo) and contravariant in the other (contravariantFoo). It is not declared covariant or contravariant upfront; instead, its variance is defined at the point where it is used (use-site).</p><p>In Scala you can do the same thing, just with a somewhat different syntax (using [_ &lt;: Integer] and [_ &gt;: Integer] respectively), but you can also declare variance upfront (declaration-site):</p><pre>class CovariantFoo[+T] { ... }<br>class ContravariantFoo[-T] { ... }<br>...<br>val covariantFoo = new CovariantFoo[Int]()<br>val contravariantFoo = new ContravariantFoo[Int]()</pre><p>This time we have two classes, each declaring its type parameter as being covariant or contravariant. Here’s a brief summary:</p><pre><strong>Covariance</strong>                           <br>if A is a <em>subtype</em> of B then:<br>Java:  L&lt;A&gt; is a subtype of L&lt;? extends B&gt; (use-site)<br>Scala: L[A] is a subtype of L[_ &lt;: B]      (use-site)<br>       L[A] is a subtype of L[+B]          (declaration-site)</pre><pre><strong>Contravariance</strong><br>if A is a <em>supertype</em> of B then:<br>Java:  L&lt;A&gt; is a subtype of L&lt;? super B&gt; (use-site)<br>Scala: L[A] is a subtype of L[_ &gt;: B]    (use-site)<br>       L[A] is a subtype of L[-B]        (declaration-site)</pre><p>Which approach is better, use-site or declaration-site? Well, neither is generally better. They are different ways to achieve something. I personally prefer declaration-site variance because it goes well with the whole “immutable therefore easy to reason about” functional paradigm (Scala also allows you to write in an imperative, non-functional way, but it is highly discouraged). Once you declare the variance of your type parameter(s), there’s no messing around them and changing them in the rest of the code.</p><p>Also, it’s better to put the burden of declaring variance on yourself since you are the designer; if you put that burden on the clients of your class, they may misuse it. To cite Programming in Scala [1]:</p><blockquote>[With use-site variance] It will be the clients of the class that need to put in the wildcards, and if they get it wrong, some important instance methods will no longer be applicable. Variance being a tricky business, users usually get it wrong, and they come away thinking that wildcards and generics are overly complicated. With definition-site variance you express your intent to the compiler, and the compiler will double check that the methods you want available will indeed be available.</blockquote><p>What exactly does Scala compiler double check? It checks if you are violating the <strong>rules of covariance and contravariance</strong> in your method definitions by using covariant types in contravariant positions and vice versa. Note that this is in direct relation to the get — put principle; it’s just a bit more generalized version of it. We could call it the <em>covariant position — contravariant position </em>principle. It says that covariant types can serve as method return types, but not as method parameter types, while it’s the other way around for contravariant types.</p><p>Let’s see an example. We could revisit our old example from the get-put; it claimed that, in case there was no get-put principle, “we could create a list of sports cars, safely assign it to a List&lt;Car&gt; variable and then put limos inside”. Now, since <a href="https://javarevisited.blogspot.com/2018/01/10-reasons-to-learn-scala-programming.html#axzz5qk6KSalU">Scala</a> favors immutable values, this wouldn’t be so bad. Our old list of sports cars would remain a list of sports cars, while the new list would be a list of all kinds of cars. There’s no danger of adding limos to a sports-cars-only list. So let me use a better example for the rules of covariance and contravariance.</p><p>If Foo[T] is covariant in its type T, that means we can treat some Foo[SportsCar] as a Foo[Car], right? OK, but if Foo[SportsCar] is a subclass of Foo[Car], then it must support all methods from the Foo[Car] (and possibly add some of its own, more specific ones). Now, what if Foo has some method that uses the value of type T as its parameter<em> </em>(that is, in contravariant position)? This particular method would have no problem accepting a limo in Foo[Car], but now in Foo[SportsCar] all of a sudden it only accepts sports cars! We would have an invocation which works in a superclass (passing a limo to that method), but not in a subclass. This would be a violation of the whole subclass-superclass concept. Methods which return values of type T are OK since returning a sports car obeys the obligation from the superclass to return a car.</p><p>It’s the other way around for classes that are contravariant in its type. Passing T into methods would be OK — since Foo is contravariant in its type, it means that subclasses of Foo are all those that are parameterized by Car’s supertype, such as Foo[Vehicle] or Foo[Any]. Method taking a Car would, in that case, become a method taking a Vehicle or Any. This is OK. What must be obeyed is that methods taking a Car in original class must be able to take a Car in the subclass instead of narrowing it down as we saw in the SportsCar example. And this is indeed fulfilled. Any code that may be using Foo[Car]’s methods to feed it with cars will also work if we substitute Foo[Car] for one of its subclasses, such as Foo[Vehicle]. Feeding cars to a method taking a Foo[Vehicle] is just fine.</p><p>But now in the case of Foo being contravariant we run into problems when we want to have a method return a value of type Car. In case of covariance, it would return limos, sport cars, AstonMartins etc. and they are all, in fact, cars. However, being a Foo[Car] and having your subclass return a Foo[Vehicle] (don’t forget that Foo is contravariant so its subclass must be parameterized by Car’s supertype) wouldn’t be quite right, because the whole point of having a subclass is that you can plug it in at any place where its parent class is needed, and that wouldn’t be possible in this case. Using a subclass such as Foo[Vehicle] would restrict the results of our method calls to vehicles, which means our old code would no longer work (perhaps it invokes “slam the door” on the result, but what it really got as a result was a motorcycle; method only promised us with a vehicle, remember?). Don’t worry if this is kind of hard to digest. It really isn’t a trivial thing to wrap your mind around. In the next section I will provide a richer example for contravariance and things should fall into place by the time you’re done with this article.</p><p>Back to our rules. So, declaration-site variance allows the compiler to check if rules of covariance and contravariance are obeyed. If you use use-site variance, however, your compiler cannot help you with these rules since it doesn’t know whether your class is covariant or contravariant in its type (or each of its types). The variance declaration is postponed until the point where the class is used. This means that you, as a designer of the class, have no control over these things. You will define your class methods and you will pray that future users of your class will invoke get-like methods only when they instantiate your class as covariant and invoke put-like methods only when they instantiate it as contravariant. The covariance/contravariance hassle is now on their hands. I don’t know about you, but I prefer to take this ugly work on myself and make their lives easier.</p><p>In the next (and final) section I will provide an example for variance in Scala by subtyping a function. Functions in Scala are first-grade citizens; not only can they be passed around as parameters, returned from methods, held in collections etc., but they can also be subtyped and supertyped. So instead of just having subclasses and superclasses, you can also have subfunctions and superfunctions!</p><h4>Variance in function subtyping</h4><p>Each one-parameter function in Scala is actually an implementation of Function1 trait (in reality it’s a bit more complicated, but details are omitted here for brevity):</p><pre>trait Function1[-S, +T] { def apply(x: S): T }</pre><p>Notice that Function1 is contravariant in S and covariant in T. Some implementation of Function1 trait (let’s call it MySubFunction[S1, T1]) is a subclass of another (let’s call it MySuperFunction[S2, T2]) only if it obeys the variance rules provided in Function1 (that is, if S2 &lt;: S1 and T1 &lt;: T2).</p><p>This rule of function being covariant in its input type and contravariant in its return type comes from the <em>Liskov substitution principle </em>(LSP). It says that T is a subtype of U if it supports the same operations as U and all of its operations <strong>require less</strong> (or same)<em> </em>and <strong>provide more </strong>(or same) than the corresponding operations in U (subtyping is reflexive so S &lt;: S).</p><p>OK, let’s see what that means. Think of a function:</p><pre>def getCarInfo: Car =&gt; AnyRef</pre><p>These are all valid sub-types of getCarInfo:</p><ul><li>Car =&gt; AnyRef</li><li>Vehicle =&gt; AnyRef</li><li>Car =&gt; String</li><li>Vehicle =&gt; String</li></ul><p>They all require less (or same) and provide more (or same) as Car =&gt; AnyRef. “Less” means “more general” and “more” means “more specific”. This is very logical: Vehicle is “less than” Car because we know less of the object (we only know that it’s a vehicle, but not which kind of vehicle), whereas it is “more than” AnyRef because it provides us with more than just an AnyRef object (we have all the fields and methods defined in Vehicle).</p><p>Let’s take a closer look at these four subtypes. First one is exactly the same as getCarInfo, and that’s OK because subtyping is reflexive (that’s why I added “or same” after less/more in the definition of LSP); second one requires less, because it doesn’t restrict us to just cars — it allows any vehicle, which is a lesser requirement than cars; third one provides more, because instead of providing us with just an AnyRef, it provides us with a much richer type String; and the fourth one both requires less and provides more than getCarInfo.</p><p>Stop and think about it for a second. This is covariance and contravariance in its full glory! If I want function B to be a <strong>subtype</strong> of function A, then B’s input parameter must be a <strong>superclass</strong> of A’s input parameter (contravariance) and B’s return value must be a <strong>subclass</strong> of A’s return value (covariance).</p><p>Let’s build a full example now. Here’s the code:</p><pre>1   /**<br>2    * Remember! In Scala, every function that takes one argument <br>3    * is an instance of Function1 with signature:<br>4    *<br>5    * trait Function1[-T, +S] extends AnyRef<br>6    */<br>7   <br>8   class Vehicle(val owner: String)<br>9   class Car(owner: String) extends Vehicle(owner)<br>10  <br>11  object Printer {<br>12<br>13    val cars = List(new Car(&quot;john&quot;), new Car(&quot;paul&quot;))<br>14<br>15    def printCarInfo(getCarInfo: Car =&gt; AnyRef) {<br>16      for (car &lt;- cars) println(getCarInfo(car))<br>17    }<br>18  }<br>19  <br>20  object Customer extends App {<br>21<br>22   val getOwnerInfo: (Vehicle =&gt; String) = _.owner<br>23   <br>24   Printer.printCarInfo(getOwnerInfo)<br>25  }</pre><p>Look at the method printCarInfo (line 15) that takes a function Car =&gt; AnyRef as a parameter:</p><pre>def printCarInfo(getCarInfo: Car =&gt; AnyRef)</pre><p>If we are to invoke this method from our custom code (line 24), we must either pass a function with the identical signature (Car =&gt; AnyRef), or a function that’s a subtype of Car =&gt; AnyRef, that is, which requires less or same and provides more or same as Car =&gt; AnyRef. In the example we go for the second option and pass in a function (defined in line 22) that requires less than Car (a Vehicle) and provides more than AnyRef (a String):</p><pre>val getOwnerInfo: (Vehicle =&gt; String) = _.owner</pre><p>Good, LSP is satisfied, so our function Vehicle =&gt; String is a valid subtype of Car =&gt; AnyRef.</p><p>Method printCarInfo uses the function getCarInfo in line 16 to get info from a car and print it out. Even if printCarInfo code was not available to us and we couldn’t see inside the method, we would still know that it must be feeding cars (don’t forget that this also includes subtypes, e.g. AstonMartin) to getCarInfo. Its signature tells us that. So if we say that our substitute function for getCarInfo takes a Vehicle, we didn’t break anything, since all cars and their subtypes are also vehicles. All we did was that we provided a function that <em>requires less</em>, so printCarInfo will not notice anything different. What printCarInfo says is— “cool, whatever, as long as you provide me with a function that will accept my cars, I’m fine”. And a function that accepts vehicles surely accepts cars.</p><p>On the other hand, our Vehicle =&gt; String returns a String, which means it <em>provides more</em>. What printCarInfo said is that it wants a function returning an AnyRef. Is String an AnyRef? Yes, it is. Again, we didn’t break anything.</p><p>Great! We have shown that Vehicle =&gt; String is a perfectly valid substitute for Car =&gt; AnyRef. PrintCarInfo will continue its workflow normally without ever noticing that instead of Car =&gt; AnyRef it was provided a Vehicle =&gt; String instead. And we have seen contravariance, that weird little member of the variance family, in a real example instead of some esoteric theoretical explanation.</p><p>So there you have it. My attempt at explaining variance stops here. If you want to give me some feedback, feel free to contact me at sinisalouc@gmail.com.</p><h4>References</h4><p>[1]: Martin Odersky, Lex Spoon, Bill Venners, “<a href="http://www.amazon.com/dp/0981531644/?tag=javamysqlanta-20">Programming in Scala”, 2nd Edition</a></p><h4><strong>Further Learning</strong></h4><p><a href="http://javarevisited.blogspot.sg/2017/04/5-books-to-learn-scala-and-functional-programming.html">5 Books to Learn Scala and Functional Programming</a><br><a href="https://hackernoon.com/10-reasons-to-learn-scala-and-functional-programming-2fce385e6ec7">10 Reasons to Learn Scala</a> on <a href="https://medium.com/u/4a8a924edf41">Hackernoon</a><br><a href="https://hackernoon.com/a-10-minute-introduction-to-scala-d1fed19eb74c">A 10-Minute Introduction to Scala</a> by <a href="https://medium.com/u/1c96b0f1c413">Teiva Harsanyi</a><br><a href="https://javarevisited.blogspot.com/2019/01/5-free-scala-programming-courses-for-java-programmers-learn-online.html">5 Free Courses to Learn Scala </a><br><a href="https://javarevisited.blogspot.com/2017/03/top-30-scala-and-functional-programming.html">Top 30 Scala Programming Interview Questions</a><br><a href="https://medium.com/@sderosiaux/a-guide-to-introduce-scala-in-a-java-world-327b932699b4">A case to introduce Scala in a Java world</a> by <a href="https://medium.com/u/1b989e65c718">Stéphane Derosiaux</a></p><ul><li><a href="https://medium.com/javarevisited/7-free-scala-and-functional-programming-courses-for-beginners-370f3cd41a4e">7 Free Scala and Functional Programming Courses for Beginners in 2022</a></li><li><a href="https://medium.com/javarevisited/10-best-scala-and-functional-programming-online-courses-for-beginners-b6461b27bf">10 Best Scala Courses and Tutorials to Learn Functional Programming in 2024</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63af925d21dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/variance-in-java-and-scala-63af925d21dc">Variance in Java and Scala</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>