<?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[Karol Chmist - Medium]]></title>
        <description><![CDATA[Blog - Medium]]></description>
        <link>https://medium.com/karol-chmist?source=rss----adc47ae0fce1---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Karol Chmist - Medium</title>
            <link>https://medium.com/karol-chmist?source=rss----adc47ae0fce1---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 09:12:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/karol-chmist" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Composing monadic functions with Kleisli]]></title>
            <link>https://medium.com/karol-chmist/composing-monadic-functions-with-kleisli-4ef2f9a2d6c5?source=rss----adc47ae0fce1---4</link>
            <guid isPermaLink="false">https://medium.com/p/4ef2f9a2d6c5</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[cats]]></category>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[kleisli]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Karol Chmist]]></dc:creator>
            <pubDate>Sat, 05 May 2018 06:55:55 GMT</pubDate>
            <atom:updated>2018-10-17T09:17:28.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AFpFQ85ufJAhT8kQ." /><figcaption>Photo by <a href="https://unsplash.com/@milkovi?utm_source=medium&amp;utm_medium=referral">MILKOVÍ</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We all love chaining monadic operations.</p><p>In Scala, we could write :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d0290024cf45d890bbe7fe4b4bf88a6/href">https://medium.com/media/2d0290024cf45d890bbe7fe4b4bf88a6/href</a></iframe><p>It’s a powerful concept that let us chain method calls that return a monad.</p><p>But sometimes a for-comprehension is too powerful for our needs.</p><p>What if we wanted only to compose these methods ?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91255afa88e787713236d845464c41c6/href">https://medium.com/media/91255afa88e787713236d845464c41c6/href</a></iframe><p>It won’t work since the types are as follows :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ed767989b730d35183caf5eb902d637/href">https://medium.com/media/4ed767989b730d35183caf5eb902d637/href</a></iframe><p>and the composition would work only if it were in this form :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e177ec365b00f4b1cfe3f070da9d290/href">https://medium.com/media/4e177ec365b00f4b1cfe3f070da9d290/href</a></iframe><p>I didn’t know a structure that could do that, so I’ve searched a bit, and I’ve found a Kleisli. It is pretty simple: just a wrapper around functions returning a monad (or another algebraic structure). It gives a bunch of functions that we can use as with a normal functions, like “andThen”, “compose” etc. Kleisli just abstracts for us the fact that function returns a monad.</p><p>Here is a simple example, that will be described below in details :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ca2cfd72f7541ab5ae5ce9246699aa7/href">https://medium.com/media/3ca2cfd72f7541ab5ae5ce9246699aa7/href</a></iframe><p>Let’s break it down.</p><p>First, let’s have a look at how to create a Kleisli by passing a function in its constructor :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9baf2f3eec5a570d144ccb50beef67d9/href">https://medium.com/media/9baf2f3eec5a570d144ccb50beef67d9/href</a></iframe><p>In our case the functions return an Either, which stores a value of one of two types, called Left or Right. Usually, on the Left we store an error, and on the Right we store the right (correct) value.</p><p>There was one problem I found when using Kleisli with Either : it allows a monad with only one data parameter. Its constructor is as follows :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45be19344631c86d0adebd900136395a/href">https://medium.com/media/45be19344631c86d0adebd900136395a/href</a></iframe><p>In our case, the F represents a monad, and our function should return an instance of a monad with B.</p><p>Either is defined as follows, with two type parameters:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a779b68f6f70a54fab45063ac7378d5/href">https://medium.com/media/4a779b68f6f70a54fab45063ac7378d5/href</a></iframe><p>I needed to hide that fact for Kleisli, but I got stuck. So I asked on stack overflow and the solution was to hide the “fixed” error type by creating a new type with only one type parameter :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6d94b5c02dea35dd9ae74ebfe264f8d/href">https://medium.com/media/c6d94b5c02dea35dd9ae74ebfe264f8d/href</a></iframe><p>Then, to make it compile, I needed to create two new functions that convert an Either to this new ErrorOr type :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95a5a633a870961928b1427c9d2e5857/href">https://medium.com/media/95a5a633a870961928b1427c9d2e5857/href</a></iframe><p>The rest is just an example of composing our functions and running it.</p><p>It is worth noting that Kleisli accepts not only monads but other structures defined in Cats, like Functors, Applicatives etc.</p><p>You can find more on Kleisli here : <br><a href="https://typelevel.org/cats/datatypes/kleisli.html">https://typelevel.org/cats/datatypes/kleisli.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ef2f9a2d6c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/karol-chmist/composing-monadic-functions-with-kleisli-4ef2f9a2d6c5">Composing monadic functions with Kleisli</a> was originally published in <a href="https://medium.com/karol-chmist">Karol Chmist</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stacking monads with FutureEither]]></title>
            <link>https://medium.com/karol-chmist/stacking-monads-with-futureeither-6e50385a0a7?source=rss----adc47ae0fce1---4</link>
            <guid isPermaLink="false">https://medium.com/p/6e50385a0a7</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Karol Chmist]]></dc:creator>
            <pubDate>Fri, 15 Jan 2016 10:55:49 GMT</pubDate>
            <atom:updated>2016-01-14T15:10:27.401Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will show how we can stack two monads by creating a new one.</p><h4>Problem</h4><p>Let’s say you have a Scala project. You have some blocking operations (like accessing a database or calling a service over the network), so you use Scala’s <a href="http://docs.scala-lang.org/overviews/core/futures.html">Future</a>. Also, you want to avoid using exceptions, so you decide to use <a href="http://stackoverflow.com/questions/18352079/scala-either-orelse-method">Either</a>, storing the error on the left side, and the result on the right side.</p><p>Maybe you’d be better off using <a href="https://github.com/scalaz/scalaz">Scalaz</a> with <a href="http://timperrett.com/2014/07/20/scalaz-task-the-missing-documentation/">Task</a> or <a href="http://eed3si9n.com/learning-scalaz/Either.html">\/</a>. Yes, at the same time, Scalaz may be too <a href="http://jimplush.com/talk/2015/12/19/moving-a-team-from-scala-to-golang/">complex</a> for your team. So let’s say that, for whatever reason, we decide not to use it.</p><p>Usually, we need to combine several blocking calls, each of which may fail with an error. Therefore, we may decide to model the calls with a Future[Either[Error,A]] structure.</p><h4>Example - sending an email</h4><p>Here’s an example of such a code, creating a mail and sending it to a user :</p><pre><strong>import </strong>scala.concurrent.Future<br><br><strong>case class </strong>Person(id: String, name:String, email: String)<br><strong>case class </strong>MailTemplate(id: String, template: String)<br><strong>case class </strong>Mail(recipient: Seq[String], body: String)<br><strong>case class </strong>Error(message: String)</pre><pre><strong>type </strong>Result[A] = Future[Either[Error, A]]</pre><pre><strong>def </strong>sendMail(personId: String,<br>             mailTemplateId: String): Result[String] =<br>  <strong>for </strong>{<br>    errOrPerson &lt;- findPerson(personId)<br>    errOrMailTemplate &lt;- findMailTemplate(mailTemplateId)<br>    errOrMail = createMailIfNoError(errOrPerson, errOrMailTemplate)<br>    errOrSendMailStatus &lt;- sendMailIfNoError(errOrMail)<br>  } <strong>yield </strong>maybeSendMailError</pre><p>So we look for a person in the DB, we construct a mail from the template and we send it. At the end, we return an “OK” if everything went well.</p><p>There’s a Result[A] type defined as well, so that we have less noise in the returning types.</p><h4>Stubbed service calls</h4><p>Here are the calls with stubbed implementations. The details are not important, the types of signatures are more interesting here:</p><pre><strong>def </strong>findPerson(id: String): Result[Person] = <br><em>  Future</em>(<em>Right</em>(<em>Person</em>(id, &quot;John&quot;, &quot;example@t.com&quot;)))</pre><pre><strong>def </strong>findMailTemplate(templateId: String): Result[MailTemplate] = <br><em>  Future</em>(<em>Right</em>(<em>MailTemplate</em>(templateId, &quot;Hi %NAME, How are you?&quot;)))</pre><pre><strong>def </strong>createMail(person: Person, <br>               mailTemplate: MailTemplate): Either[Error, Mail] = <br><em>  Right</em>(<em>Mail</em>(<em>Seq</em>(person.email),  <br>             mailTemplate.template.replaceAll(&quot;%NAME&quot;, person.name)))</pre><pre><strong>def </strong>sendMail(mail: Mail): Result[String] = <br>  Future.<em>successful</em>{<br>  <em>  println</em>(s&quot;Sending <strong>$</strong>mail&quot;)<br>  <em>  Right</em>(&quot;OK&quot;)<br>  }</pre><p>NB : When using Futures, we must provide an ExecutionContext. We can import a global one:</p><pre><strong>import </strong>scala.concurrent.ExecutionContext.Implicits.<em>global</em></pre><p>But the <a href="https://github.com/alexandru/scala-best-practices/blob/master/sections/4-concurrency-parallelism.md#411-must-not-hardcode-the-thread-pool--execution-context">correct way</a> of providing it, is by an implicit parameter, e.g.:</p><pre><strong>def </strong>findPerson(id: String)<br>              (<strong>implicit </strong>ec:ExecutionContext): Result[Person] = ...</pre><h4>Error handling - the manual way</h4><p>Going back to the code. Unfortunately, we need to treat the errors as well:</p><pre><strong>def </strong>createMailIfNoError(<br>          errOrPerson: Either[Error, Person],<br>          errOrMailTemplate: Either[Error, MailTemplate])<br>          : Either[Error, Mail] =<br>  <strong>for </strong>{<br>    person &lt;- errOrPerson.right<br>    mailTemplate &lt;- errOrMailTemplate.right<br>    mail &lt;- createMail(person, mailTemplate).right<br>  } <strong>yield </strong>mail<br><br><strong>def </strong>sendMailIfNoError(errOrMail: Either[Error, Mail])<br>    : Result[String] =<br>  errOrMail.fold(<br>    err =&gt; Future.<em>successful</em>(<em>Left</em>(err)),<br>    mail =&gt; sendMail(mail)<br>  )</pre><p><em>Either</em> in Scala is unbiased, and to use it in a monadic way, we choose which side is the correct one (<em>right</em> conventionally). So we can make our life easier with the for-comprehension, like in the <em>createMailIfNoError</em> function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*QE9KkBeVknBKKvbG7tTACw.jpeg" /><figcaption><a href="https://commons.wikimedia.org/wiki/File:Jenga_distorted.jpg#/media/File:Jenga_distorted.jpg">By Guma89. Licensed under CC BY-SA 3.0 via Commons</a></figcaption></figure><p>Or we can fold it, meaning we provide a return value for both scenarios. Here in the <em>sendMailIfNoError</em> method, in case of an error (the <em>left</em> case), we just return immediately with <em>Future.successful</em>. (Just to be clear, successful here means that we don’t create a new process. We still return an error inside.) Otherwise, we send the mail and we return the result.</p><p>If most of our services are designed this way, they may become tiresome and prone to error. What we do is pretty repetitive: while staying in the <em>Future</em> context, return an error if it has occurred; otherwise proceed. Is there a simpler way?</p><h3>Solution</h3><p>Let’s create our own monadic structure to get rid of the fluff and stay <a href="https://en.wikipedia.org/wiki/Don&#39;t_repeat_yourself">DRY</a>!</p><p>To have a <a href="http://stackoverflow.com/questions/25361203/what-exactly-makes-option-a-monad-in-scala/25361305#25361305">monad in Scala</a> , we need at least a <em>flatMap</em> function. Let’s also add <em>map</em> and <em>fold</em> functions while we’re at it. We can call it FutureEither for the lack of a better name:</p><pre><strong>case class </strong>FutureEither[A,+B](inner: Future[Either[A, B]]) {<br><strong> </strong> <strong>def </strong>flatMap[C](f: B =&gt; FutureEither[A,C])<br>                 (<strong>implicit </strong>ec: ExecutionContext): FutureEither[A,C] =<br>    <em> FutureEither</em>(<br>       inner.flatMap(_.fold(<br>         error =&gt; Future.<em>successful</em>(<em>Left</em>(error)),<br>         value =&gt; f(value).inner<br>       ))<br>     )<br><strong>  <br>  def </strong>map[C](f: B =&gt; C)<br>             (<strong>implicit </strong>ec: ExecutionContext): FutureEither[A,C] =<br><em>     FutureEither</em>(inner.map(_.right.map(f)))</pre><pre><strong>  def </strong>fold[C](e: A =&gt; C, s: B =&gt; C)<br>             (<strong>implicit </strong>ec: ExecutionContext): Future[C] =<br>    inner.map(_.fold(e, s))<br><br>  <strong>def </strong>run : Future[Either[A, B]] = inner<br>}</pre><p>Basically, we have a biased-to-the-right <em>Either</em> packed in a <em>Future</em>.</p><p>The <em>flatMap </em>takes a function as a parameter, producing a new FutureEither that is only evaluated if its current <em>Either</em> is on the right side. Otherwise, the current error is kept.</p><p>The <em>map</em> function accepts a parameter transforming the right side of the <em>Either</em>.</p><p>Digression: we can see that while <em>flatMap</em> may change the branching of the monad (depending on the result of the function output), <em>map</em> only transforms the inner right value. Therefore one might say that <em>map</em> is less powerful than <em>flatMap.</em></p><p>The <em>fold</em> function defines a transformation, joining both sides to a new common type. It’s the same functionality as in the standard <em>Either</em>, but the result will stay in the <em>Future</em> context.</p><p>Finally, if we just need to obtain the raw Future[Either[A,B]], we can use the <em>run</em> function.</p><h4>Monad construction</h4><p>To construct our FutureEither, we can pass an already existing Future[Either[A,B]] to the constructor, like this:</p><pre><strong>val </strong>eventualResult: Future[Right[Error, Int]] = Future(<em>Right</em>(1 + 2))</pre><pre><strong>val </strong>wrapped: FutureEither[Error, Int] = <em>FutureEither</em>(eventualResult)</pre><p>In case we need to create our FutureEither from a simpler type, let’s define helping functions in the companion object:</p><pre><strong>object </strong>FutureEither {<br>  <strong>def </strong>failure[A,B&lt;:Any](a: A): FutureEither[A,B] = <em>FutureEither</em>(Future.<em>successful</em>(<em>Left</em>(a)))<br><br>  <strong>def </strong>point[A&lt;:Any,B](b: B): FutureEither[A,B] = <em> <br>    FutureEither</em>(Future.<em>successful</em>(<em>Right</em>(b)))<br><br>  <strong>def </strong>pointFromFuture[A&lt;:Any,B]<br>           (fb: Future[B])<br>           (<strong>implicit </strong>ec: ExecutionContext): FutureEither[A, B] = <br><em>    FutureEither</em>(fb.map(b =&gt; <em>Right</em>(b)))<br><br>  <strong>def </strong>failureFromFuture[A,B&lt;:Any]<br>           (fa: Future[A])<br>           (<strong>implicit </strong>ec: ExecutionContext): FutureEither[A,B] = <br><em>    FutureEither</em>(fa.map(a =&gt; <em>Left</em>(a)))<br><br>  <strong>def </strong>fromEither[A,B](a: Either[A, B]): FutureEither[A,B] = <br><em>    FutureEither</em>(Future.<em>successful</em>(a))<br>}</pre><p>Looking at the signatures, it’s pretty easy to guess when we can use them.</p><p>The <em>failure</em> function uses a “bare” left side, the <em>point</em> one uses the right side. There are also *fromFuture functions that only wrap already existing Future values into an <em>Either</em>. Finally, we can wrap an <em>Either</em> in a <em>Future</em> with the <em>fromEither</em> function.</p><h4>Improved example</h4><p>Let’s look at our original example of sending an e-mail using the new monad:</p><pre><strong>type </strong>Result[A] = FutureEither[Error, A]</pre><pre><strong>def </strong>sendMailToPerson(personId: String,<br>                     mailTemplateId: String): Result[String] =<br>  <strong>for </strong>{<br>    person &lt;- findPerson(personId)<br>    mailTemplate &lt;- findMailTemplate(mailTemplateId)<br>    mail = createMail(person, mailTemplate)<br>    sendMailStatus &lt;- sendMail(mail)<br>  } <strong>yield </strong>sendMailStatus</pre><p>We don’t need <em>createMailIfNoError </em>and<em> sendMailIfNoError</em> anymore! The “service” functions are slightly different:</p><pre><strong>def </strong>findPerson(id: String): Result[Person] = <br>  FutureEither.point(Person(id, &quot;Mary&quot;, &quot;test2@example.com&quot;))</pre><pre><strong>def </strong>findMailTemplate(templateId: String): Result[MailTemplate] =  <br>  FutureEither.<em>point</em>(<br><em>    MailTemplate</em>(templateId, &quot;Hi %NAME, How are you?&quot;)<br>  )</pre><pre><strong>def </strong>createMail(person: Person, mailTemplate: MailTemplate): Mail = <br><em>  Mail</em>(<br><em>    Seq</em>(person.email), <br>    mailTemplate.template.replaceAll(&quot;%NAME&quot;, person.name)<br>  )</pre><pre><strong>def </strong>sendMail(mail: Mail): Result[String] = <br>  FutureEither.<em>point </em>{<br>  <em>  println</em>(s&quot;Sending <strong>$</strong>mail&quot;)<br>    &quot;OK&quot;<br>  }</pre><h4>Conclusion</h4><p>I am a big fan of learning and using advanced concepts in Functional Programming, but sometimes we can use a simple DIY solution to solve a problem.</p><p>I’ve put the code on the <a href="https://github.com/karolchmist/scala-fp-utils/blob/master/src%2Fmain%2Fscala%2Fcom%2Fchmist%2Fscala%2Ffp%2Futils%2FFutureEither.scala">github</a>, so you can copy and paste it in your project if you find it useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e50385a0a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/karol-chmist/stacking-monads-with-futureeither-6e50385a0a7">Stacking monads with FutureEither</a> was originally published in <a href="https://medium.com/karol-chmist">Karol Chmist</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>