<?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 Idris Kabir on Medium]]></title>
        <description><![CDATA[Stories by Idris Kabir on Medium]]></description>
        <link>https://medium.com/@abu_nadhr?source=rss-267a344f59a8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KjWVVxr6VmzxgBiHjszWsg.jpeg</url>
            <title>Stories by Idris Kabir on Medium</title>
            <link>https://medium.com/@abu_nadhr?source=rss-267a344f59a8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 23:30:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abu_nadhr/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[What We Learned When We Rewrote Zainpay’s Backend in Rust]]></title>
            <link>https://medium.com/@abu_nadhr/what-we-learned-when-we-rewrote-zainpays-backend-in-rust-4aa90c67fade?source=rss-267a344f59a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aa90c67fade</guid>
            <category><![CDATA[zainpay-goes-rust]]></category>
            <dc:creator><![CDATA[Idris Kabir]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 15:14:35 GMT</pubDate>
            <atom:updated>2026-08-07T15:14:35.347Z</atom:updated>
            <content:encoded><![CDATA[<p>In early 2021, <a href="https://zainpay.ng/">Zainpay</a>’s entire backend ran on a technology stack most business owners have never heard of: Scala and something called Akka. To our engineering team, it was elegant. The “actor model” — a way of handling thousands of simultaneous payment requests without them crashing into each other — felt like the right foundation for a payments company.</p><p>And for a while, it was.</p><p>But two years later, that same foundation became a technical debt.</p><h3>The Licensing Shock</h3><p>In 2022, the company behind <a href="https://akka.io/blog/why-we-are-changing-the-license-for-akka">Akka changed its license</a>. What had been free to use now required a commercial contract for production environments. The bill wasn’t public, but for a startup operating on Nigerian margins, “enterprise pricing” meant one thing: unaffordable.</p><p>We looked at staying on the old open-source version. It was technically possible — like driving a car with no service history. It moves, until it doesn’t. For a platform handling other people’s money, “probably fine” isn’t a strategy.</p><h3>The Talent Wall</h3><p>Here’s something they don’t tell you in startup blogs: your technology choices determine who you can hire.</p><p>Scala is powerful. It’s also difficult. The learning curve isn’t steep — it’s a cliff. Advanced type systems, functional programming patterns, and the mental model of actors managing messages across a system… these aren’t skills you pick up in bootcamps.</p><p>In northern Nigeria(Kano, to be precise), where Zainpay is based, the pool of developers with production Scala experience was practically a puddle. Every new hire required months of training before they could touch production code. Every departure cost us institutional knowledge we couldn’t afford to lose.</p><p>We were optimizing for engineering purity while our hiring pipeline dried up.</p><h3>The Search</h3><p>We needed something different. Four things, specifically:</p><ol><li><strong>Safety first.</strong> When you’re moving money, a memory leak isn’t a bug — it’s a liability. We needed guarantees, not hope.</li><li><strong>Predictable speed.</strong> Payment processing doesn’t pause for garbage collection. We needed performance we could count on under load.</li><li><strong>Future-proofing.</strong> Crypto and blockchain weren’t buzzwords to us. They were directions we needed the option to go.</li><li><strong>People we could actually hire.</strong> A brilliant language means nothing if you can’t find developers to write in it.</li></ol><p>We evaluated options. Rust kept surfacing.</p><h3>Why Rust</h3><p>Rust’s core idea is simple: the compiler prevents you from writing code that crashes or leaks memory. Not through runtime checks that slow things down — through rules enforced before your code ever runs. Data races? Caught. Memory leaks? Prevented. The guarantees are mathematical, not managerial.</p><p>For concurrency, we moved from Akka’s actor model to Tokio, Rust’s async runtime. It gave us the same ability to handle thousands of simultaneous payment flows, but without the licensing baggage or the cognitive overhead of managing actor lifecycles.</p><p>For our web layer, Actix — a Rust framework — benchmarked among the top three globally for speed and concurrency. We weren’t sacrificing performance for safety. We were getting both.</p><h3>The Migration</h3><p>Rewriting a live payments platform is like replacing an engine while the car is on the highway. One wrong move and you’re explaining to merchants why their money disappeared.</p><p>We didn’t rush.</p><p>We started with the most critical piece: the transaction engine. Ported it to Rust. Kept the same API endpoints and request formats so our merchants wouldn’t notice. Ran both systems side by side under a single load balancer, watching every metric.</p><p>Our clients noticed something eventually. Payments settled faster. Downtime became rare. The platform felt… solid.</p><p>Then we looked at our infrastructure bill.</p><p>A basic server — 2 GB of RAM, 80 GB of storage — was now handling workloads that previously demanded far more. The efficiency wasn’t marginal. It was transformative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xhkt9rCTiaj4nNuYeB0IhQ.jpeg" /></figure><h3>Where We Are Now</h3><p>Rust runs 80% of <a href="https://zainpay.ng/">Zainpay</a>’s backend today.</p><p>The decision wasn’t about chasing a trendy language. It was about three hard realities: a license we couldn’t afford, a talent market we couldn’t access, and a reliability standard we couldn’t compromise.</p><p>Every technology choice is a bet. Some bets pay off immediately. Others cost you before you realize you’re losing. Our Scala bet was right until it wasn’t. The Rust bet? So far, it’s holding.</p><p><strong>The lesson, if there is one:</strong> The best technology for your business isn’t the most elegant. It’s the one you can afford, the one your team can master, and the one that keeps working when everything else breaks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aa90c67fade" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Akka Typed with Redis]]></title>
            <link>https://medium.com/@abu_nadhr/akka-typed-with-redis-2958be8daf16?source=rss-267a344f59a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2958be8daf16</guid>
            <category><![CDATA[akka-typed]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Idris Kabir]]></dc:creator>
            <pubDate>Thu, 30 Dec 2021 14:21:42 GMT</pubDate>
            <atom:updated>2021-12-30T14:21:42.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*LdWo8DrK2Zk6K0115oGIug.jpeg" /><figcaption>kano city(center of commerce), Nigeria. credit businessday.ng</figcaption></figure><p>The year 2021 is almost rounding up and I have not written a single article because of my tight schedules and new role as the CTO of a fintech company in Kano(Nigeria); <a href="https://zainpay.ng/">zainpay.ng</a>. I guess I should say something here about how we massively used akka typed.</p><p>In May this year, my team started a new <a href="https://akka.io/">akka</a> typed project that will heavily depend on Redis streams as it’s event store database layer. Unfortunately, the very well known akka redis library(<a href="https://github.com/etaty/rediscala">etaty</a>) seems abandoned, having zero support for typed actors in akka and as at the time of writing this article the last update was two years back(2019). I did everything humanly possible to see it work but to no avail(I even asked a question on <a href="https://stackoverflow.com/questions/67685746/creating-a-redisclient-from-a-typed-akka-behavior">stackoverflow</a> here). Fortunately, scala as a lang interpolate’s excellently with java, so therefore, We worked towards finding a java Redis library that will be a good replacement for the etaty library. I finally settled for <a href="https://github.com/redis/jedis">jedis</a> which was not only rich in terms of implement Redis features but also always up to date with more than a thousand contributors to the library.</p><p>After spending some time with jedis, We created an akka typed wrapper DSL which amusingly worked for all our projects without more hustle. Here is a sample code snippet we wrote.</p><p>First, we created a Jedis instance as an object.</p><pre><em>object </em>RedisInstance {<br><br>  <em>private val host </em>= &quot;localhost&quot;<em><br>  private val port </em>= 6379<em><br><br>  lazy val redis </em>= <em>new </em>Jedis(<em>host</em>, <em>port</em>)<br><br>}</pre><p>Next, we created a RedisDbMessage object. This object will house all Redis Command(this file grew too large so we had to divide the commands into modules, based on functionality we’re implementing)</p><pre><em>object </em><strong>RedisDbMessage</strong> {<br><br>  <em>sealed trait Command<br>  sealed trait Response<br><br>case class </em><strong>SetCmd</strong>(<br>  key: String,<br>  value: String,<br>  lifetime: Option[FiniteDuration] = None,<br>  replyTo: <em>ActorRef</em>[<em>Response</em>])<br>    <em>extends Command</em></pre><pre><em>case class </em><strong>SetRsp</strong>(<br>command: SetCmd, status: Boolean) <em>extends Response<br><br>case class </em><strong>GetCmd</strong>(key: String, replyTo: <em>ActorRef</em>[<em>Response</em>]) <br><em>extends Command</em></pre><pre><em>case class </em><strong>GetRsp</strong>(result: Option[String]) <em>extends Response</em></pre><pre><em>case class </em><strong>Failed</strong>(message: String) <em>extends Response</em></pre><p>Furthermore, we created a typed actor that interacts with the Jedis library.</p><pre><em>object </em>RedisDbService {</pre><pre><em>def </em>apply(): Behavior[RedisDbMessage.<em>Command</em>] =<br>  Behaviors.<em>receive </em>{ (context, message) =&gt;<br>    <em>implicit val </em>system           = context.system<br>    <em>implicit val </em>timeout: Timeout = 5.seconds<br>    <em>implicit val </em>ec               = context.executionContext<br><br>    <em>val </em>log = context.log<br><br>    message <em>match </em>{<br>      <em>case </em>req: SetCmd =&gt;<br>       db.<em>redis</em>.set(req.key, req.value) <em>match </em>{<br>        <em>case </em>x: String =&gt; req.replyTo ! <em>SetRsp</em>(req, <em>true</em>)<br>        <em>case </em>_ =&gt; req.replyTo ! <em>Failed</em>(&quot;failed saving to redis set!&quot;)<br>  }</pre><pre><em>case </em>req: GetCmd =&gt;<br>  db.<em>redis</em>.get(req.key) <em>match </em>{<br>    <em>case </em>x: String =&gt; req.replyTo ! <em>GetRsp</em>(<em>Some</em>(x))<br>    <em>case null </em>=&gt; req.replyTo ! <em>GetRsp</em>(None)<br>    }<br>  }<br>}</pre><p>Lastly, we can use the actor’s bang and ask patterns to set/get values from our wrapper object respectively.</p><pre>redisDbService ! SetCmd(&quot;company_name&quot;, &quot;medium.com&quot;, context.system.ignoreRef) </pre><pre>redisDbService.ask((replyTo: ActorRef[RedisDbMessage.Response]) =&gt; <br>  RedisDbMessage.GetCmd(<br>    key = &quot;company_name&quot;,<br>    replyTo = replyTo)<br>) onComplete {<br> case Success(GetRsp(Some(value))) =&gt;  log.info(s&quot;redis value found $value&quot;)</pre><pre>case Success(GetRsp(None)) =&gt; log.info(s&quot;this is empty!&quot;) <br>case Success(_) =&gt; //</pre><pre> }</pre><p>With this few lines of code we where able to get our project to production without much external dependencies. And we are hoping to out source this code into a full blown library since over the months we have implemented alot of Redis features in it. e.g piplining, Pub/Sub, Transaction e.t.c.</p><p>I hope this article was useful to you. Feel free to reach out to me if you need more explanation on this</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2958be8daf16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streaming data from PostgreSQL using Akka Streams, Akka Http and Doobie]]></title>
            <link>https://medium.com/@abu_nadhr/streaming-data-from-postgresql-using-akka-streams-akka-http-and-doobie-203ab911097c?source=rss-267a344f59a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/203ab911097c</guid>
            <category><![CDATA[akka-streams]]></category>
            <category><![CDATA[doobie]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[akka-http]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Idris Kabir]]></dc:creator>
            <pubDate>Wed, 22 Aug 2018 05:50:26 GMT</pubDate>
            <atom:updated>2018-08-22T05:50:26.560Z</atom:updated>
            <content:encoded><![CDATA[<p>This article explains my 2 days journey on building a streaming application using <a href="http://akka.io/">akka framework</a>’s akka-streams, postgres database and typelevels’s awesome JDBC library called <a href="https://tpolecat.github.io/doobie/">Doobie</a>.</p><p>It all started with my favorite PHP <a href="https://www.yiiframework.com/">framework</a> which I used to build an admin backend interface for an online application. The client requested the application to have a functionality for exporting a large sets of personnel data into csv format for offline evaluation/analysis. Firstly, been a lazy developer, I went straight using a php excel library, it was pretty straight forward to work with, but in no time I had challenges(majorly with <a href="https://stackoverflow.com/questions/32944442/yii2-allowed-memory-size-exhausted">memory</a>). These challenges were not quite easy to resolve owning to the high volume of data to be exported and the complexity of the queries which could not be implemented in a single SQL select statement.</p><p>I swiftly moved my implementation to my preferred tools for daily programming (<a href="http://akka.io/">akka framework</a>). I started with an awesome scala-csv <a href="https://github.com/tototoshi/scala-csv">library</a> by @tototoshi. It serves it purpose quite okey, but the time lap the application took to move this large data set from postgres database into a temporary file on the server and subsequently, the time it took for the application to download the temporary file through the user browser was not acceptable nor was it practical for production.</p><p>Finally, I opt to stream these records directly from postgres database to the user browser based on a few search criteria select by the end user(the client).</p><h4>My Implementation</h4><p>The process is going to be pretty straightforward in terms of this implementation where data is read from 2 tables as streams which will be a downloadable file on the user browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*6B0AkVMm1NCS5Dt0BFId5A.png" /><figcaption>Logical diagram of akka-streams implementation</figcaption></figure><p>A few dependencies to add to the project <a href="https://scala-sbt.org/">build.sbt</a> are as follows:</p><pre><em>lazy val </em>akkaHttpVersion = &quot;10.0.11&quot;<br><em>lazy val </em>akkaVersion    = &quot;2.5.11&quot;</pre><pre>libraryDependencies ++= Seq(<br>&quot;com.typesafe.akka&quot; %% &quot;akka-http&quot;            % akkaHttpVersion,<br>&quot;com.typesafe.akka&quot; %% &quot;akka-http-spray-json&quot; % akkaHttpVersion,<br>&quot;com.typesafe.akka&quot; %% &quot;akka-http-xml&quot;        % akkaHttpVersion,<br>&quot;com.typesafe.akka&quot; %% &quot;akka-stream&quot;          % akkaVersion,<br>&quot;org.tpolecat&quot;      %% &quot;doobie-postgres&quot;      % &quot;0.5.3&quot;<br>)</pre><p>Lets start by defining our case case models for the postgres database tables</p><pre><em>case class </em>Applicant(<br>    id: Int, <br>    first_name: String,<br>    surname: String,<br>    other_names: Option[String]<br>    position: String){</pre><pre> def parse(): List[String] = List(<br>  first_name,<br>  surname,<br>  other_names.getOrElse(&quot;&quot;),<br>  position)</pre><pre>}</pre><pre>case class Hobbies(<br>   applicant_id: String,<br>   hobby: String)</pre><p>Notice that we added a parse method in the applicant case class, this is necessary to ease conversion of database row to a list of strings. The relationship between the applicant table and that of the hobbies is one to many.</p><p>As earlier stated, I will be using Doobie for database connection. Doobie is a dead simple pure functional JDBC layer for Scala and <a href="http://typelevel.org/cats/"><strong>Cats</strong></a>. It is not an ORM, nor is it a relational algebra; it simply provides a principled way to construct programs (and higher-level libraries) that use JDBC. To learn more about how to compose queries with Doobie, kindly visit the <a href="https://tpolecat.github.io/doobie/">website</a>. Now lets write our doobie query to fetch these records.</p><pre><em>def </em>getApplicantList(): IO[List[Applicant]] = {<br>  sql&quot;&quot;&quot;select * from applicants<br>     &quot;&quot;&quot;.query[List[Applicant]]<br>     .stream<br>     .compile.toList<br>     .transact(xa)<em><br></em>}</pre><pre>def getApplicantWithHobbies(id: Int): IO[List[Hobbies]] = {<br>val query = sql&quot;&quot;&quot;select * from hobbies where applicant_id=$id<br>      &quot;&quot;&quot;.query[List[Hobbies]]. <br>         .stream<br>         .compile<br>         .toList<br>         .transact(xa)<br>}</pre><p>Next, is to implement the code for akka-streams(<a href="https://doc.akka.io/docs/akka/2.5.3/scala/stream/stream-flows-and-basics.html">Source and flow</a> ) and that of akka-http route.</p><pre><em>val </em>hobbiesFlow: Flow[Applicant, List[String], NotUsed] = <em>Flow</em>[Applicant].map { applicant =&gt;</pre><pre>  getApplicantWithHobbies(applicant.id).unsafeRunSync() match {<br>   case x:List[Hobbies] =&gt; applicant.parse :+            x.map(_.hobby).mkString(&quot;,&quot;) <br> <br> case _ =&gt; applicant.parse<br>}</pre><pre><em>val </em>source = <em>Source</em>(getApplicantList.unsafeRunSync())<br>  .via(hobbiesFlow)<br>  .map(x =&gt; <em>ByteString</em>(x.mkString(&quot;,&quot;) + &quot;\n&quot;))</pre><p>As you can see, we implemented an akka source using our getApplicantList method and a single flow stage which iteratively obtains the hobbies of each applicant, merge it to have a single list of strings and finally convert the list to UTF-8 encoding using ByteString method.</p><p>Lastly, we set some http custom headers in our akka-http route to enable the end user browser to download the streams of records generated.</p><pre><em>val </em>headers = List(<em>RawHeader</em>(&quot;Content-Disposition&quot;, s&quot;attachment; filename=applicant.csv&quot;))<br><br>respondWithHeaders(headers){<br>  complete(<em>HttpEntity</em>(ContentTypes.`text/csv(UTF-8)`, source))<br>}</pre><h4>Summary</h4><p>The complete akka-http route looks some what like this:</p><pre>pathPrefix(&quot;applicant-download&quot;){ <br>  get {</pre><pre><em>    val </em>source = <em>Source</em>(getApplicantList.unsafeRunSync())<br>         .via(hobbiesFlow)<br>         .map(x =&gt; <em>ByteString</em>(x.mkString(&quot;,&quot;) + &quot;\n&quot;))</pre><pre><em>    val </em>headers = List(<em>RawHeader</em>(&quot;Content-Disposition&quot;,  s&quot;attachment; filename=applicant.csv&quot;))<br><br>    respondWithHeaders(headers){<br>      complete(<em>HttpEntity</em>(ContentTypes.`text/csv(UTF-8)`, source))<br>    }<br>  }<br>}</pre><p>With these few lines of code I was able to stream a few gigabytes of records to the client without been a <em>red-neck developer</em> :)</p><p>Big thanks to <a href="https://twitter.com/Hungai">@Hungai</a> for taking the time to review this post.</p><p>Feel free to reach out to me if you need more explanation on this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=203ab911097c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Cats library for dummies — part 5]]></title>
            <link>https://medium.com/@abu_nadhr/scala-cats-library-for-dummies-part-5-8be9ffc8e869?source=rss-267a344f59a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8be9ffc8e869</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[typelevel]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[cats]]></category>
            <dc:creator><![CDATA[Idris Kabir]]></dc:creator>
            <pubDate>Tue, 10 Oct 2017 15:48:14 GMT</pubDate>
            <atom:updated>2017-10-10T15:48:14.882Z</atom:updated>
            <content:encoded><![CDATA[<h4>When OptionT is a better Option</h4><p>Have you at anytime wanted to update, filter or play around with an asynchronous response either from a database or an API call? were the response type is a scala future, option of something? something of this signature</p><pre> Future[Option[T]]</pre><p>As an example, say your response type is a Future[Option[Int]] and you want add an integer to it(before saving back to db or doing something with it). Using pure scala code you will be doing the following:</p><pre>val response = Future.successful(Option(10))</pre><pre>response.map( fut =&gt; fut.map( int =&gt; int + 30 ))</pre><p>These can be unnecessarily verbose because you have to map through the future to return the content then secondly, <em>map</em> through the option to retrieve the final value(if it exists). Here is where optionT simplifies this challenge.</p><p>The typelevel cats library optionT data type makes it easy for one to manipulate the content of <em>future</em> of an <em>option</em>. If you have played around with asynchronous database libraries such as slick, <a href="http://reactivemongo.org/">reativemongo</a>(scala mongoDB driver) or <a href="https://github.com/outworkers/phantom">phantom</a>(Scala Cassandra driver) its no news that the db IO response types are Future[Option[ResultSet]], to manipulate such return types using cats is awesome.</p><p>Continuing with the above example using cats.</p><pre>import cats.data.OptionT<br>import cats.implicits._</pre><pre><strong>val responseT = OptionT(response)</strong>  //wrapping your future option with optionT </pre><p>With this you can do all the option method manipulations like map, filter, filterNot , getOrElse.</p><pre>val responseAdded = responseT.map(_ + 30) </pre><pre>val responseWithDefault = responseT.getOrElse(5)</pre><p>Our responseT is of a type OptionT[Future,Int], if you want to return it to Future[Option[Int]] with simply do this.</p><pre>responseAdded.value</pre><p>There are other useful things you can do with typelevel cats OptionT, as this is just a simple intro. To learn more you can visit <a href="https://typelevel.org/cats/datatypes/optiont.html">here</a></p><p><em>If you like this writeup, click the💚 below so more people can see it here on Medium</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8be9ffc8e869" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Cats library for dummies- part 4]]></title>
            <link>https://medium.com/@abu_nadhr/scala-cats-library-for-dummies-part-4-b096f33cc153?source=rss-267a344f59a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b096f33cc153</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[typelevel-programming]]></category>
            <dc:creator><![CDATA[Idris Kabir]]></dc:creator>
            <pubDate>Sun, 08 Jan 2017 16:06:23 GMT</pubDate>
            <atom:updated>2017-01-16T16:34:18.252Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will center on cats library <strong>monad</strong> type class, but before we proceed, it will be nice to have a good understanding of the flatMap function in the standard scala collections. FlatMap is basically two functions in one i.e map and flatten<strong><em>. </em></strong>As an example, say we want to multiply the elements of two(2) Lists of integers and return a single list, one approach is to use the map function of the first List to iterate over the second List then combine(flatten) the final result.</p><pre>scala&gt; val first = List(2, 5)<br>first: List[Int] = List(2, 5)</pre><pre>scala&gt; val second = List(4, 8)<br>second: List[Int] = List(4, 8)</pre><pre>scala&gt; first.<strong>map</strong>( e1 =&gt; second.<strong>map</strong>(e2 =&gt; e1 * e2))<br>res0: <strong>List[List[Int]]</strong> = List(List(8, 16), List(20, 40))</pre><pre>scala&gt; res0.<strong>flatten </strong><br>res1: List[Int] = List(8, 16, 20, 40)<br> <br></pre><p>Notice how we used flatten to merge List[List[Int]] into List[Int]. Flatten can also be used for nested option types. lets see a very trivial example.</p><pre>scala&gt; val a = Option(5)<br>a: Option[Int] = Some(5)</pre><pre>scala&gt; def intToSome(x:Int) = Some(x) <br>intToSome: (x: Int)Some[Int]</pre><pre>scala&gt; a.map( o =&gt; intToSome(o))<br>res5: <strong>Option[Some[Int]]</strong> = Some(Some(5))</pre><pre>scala&gt; res5.<strong>flatten</strong><br>res6: Option[Int] = Some(5)</pre><pre>scala&gt; val a = Option(5)<br>a: Option[Int] = Some(5)</pre><pre>scala&gt; def intToSome(x:Int) = Some(x)<br>intToSome: (x: Int)Some[Int]</pre><pre>scala&gt; a.<strong>flatMap</strong>( x =&gt; intToSome(x))<br>res0: Option[Int] = Some(5)</pre><pre>scala&gt; first.<strong>flatMap</strong>( f =&gt; second.map(s =&gt; f * s))<br>res2: List[Int] = List(8, 16, 20, 40)</pre><p>In both examples flatten function was used to merge the final result into a single data type. The flatten function takes a nested context <strong>F[F[A]]</strong> to return<strong> F[A]</strong>. We can however use the flatMap function in the standard library to achieve the same computation when ever we find ourselves writing map and flatten expressions.</p><pre>F[F[A]]             =&gt; F[A]<br>Option[Option[Int]] =&gt; Option[Int]<br>List[List[Int]]     =&gt; List[Int]</pre><p>Below is the signature of the flatMap function</p><pre>def flatMap[B](f: A =&gt; F[B]): F[B]</pre><p>Remember, we discussed Applicative pure function back then in <a href="https://medium.com/@abu_nadhr/scala-cats-library-for-dummies-part-3-fd3b185088f0#.88glfnfhr">part 3</a> , now, adding flatMap to the Applicative type class gives you a Monad( any instance that have the pure and flatMap<em> </em>methods).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*q9_1eaT4Gq5KNZAfWyKrDw.jpeg" /></figure><p>We have already seen flatMap in action in our previous List and Option examples above, however, monads are in almost everywhere in all scala collections and data types(Set, Vector, Array, Map , Future* etc ), even though there is no concrete class or trait called monad in the standard scala language.</p><h3>Using Monads</h3><p>Lets have a look at an example of monad usage : say we have a student school management application and we want to implement a module that will compute the individual performance of a student for a particular session. First, we need to retrieve the student profile information, then retrieve all the courses he/she registered for that session, and finally retrieve all the grades of these courses.</p><pre>case class Grade(id:Int, studentId:Int, grade: String)<br>case class Student(id: Int, name: String)<br>case class StudentCourse(id:Int, <br>                         studentId: Int,<br>                         courseId:  Int)</pre><pre>object StudentService{<br>    def getStudentById(id: Int): Option[Student] = {}<br>}</pre><pre>object StudentCoursesService{<br>  def getCourses(student: Student): Option[List[StudentCourse]]={}<br>}</pre><pre>object StudentGrades{<br>  def getGrades(lc: List[StudentCourse]): Option[List[Grade]]={}<br>}</pre><p>Looking carefully at the return types of the service methods(options), we can simply flatmap everything.</p><pre>val studentGrade = StudentService.getStudentById(id)<br>                                 .flatMap(getCourses)<br>                                 .flatMap(getGrades)</pre><p>Alternatively, we can use the for-comprehension which is a composition of map and flatMap.</p><pre>val studentGrade = for {<br>    student &lt;- getStudentById(id)<br>    courses &lt;- getCourses(student)<br>    grades  &lt;- getGrades(courses)<br>}yield grades</pre><p>if we had to do this without using monads we will having a lot of if/then/else statement or nested loops flying everywhere (<em>where fixing a bug could possibly give you two free bugs </em>:{ ).</p><p>Libraries that are fully non-blocking with asynchronous I/O operation usually encapsulated their return types in types like futures , one example of such libraries is <a href="http://reactivemongo.org/">reactivemongo</a>. When using such libraries you will likely have to use thefuture ‘s flatmap method in composing multiple operations together.</p><h3><strong>Monads in Cats</strong></h3><p>Essentially,flatMap is the most fundamental function of Monad and authors of cats library also built its monad based on this principle — by using flatMap and pure to implement flatten and map, however, they also added another requirement to all cats library monad implementation, called tailRecM ( Tail recursive Monad), the reason behind this additional requirement is to make monadic recursion stack safe( since monadic recursion are quite common and a poor implementation could lead to stack overflow on the jvm ).</p><p>Below is a Monad implementation for Option.</p><pre>import scala.annotation.tailrec<br><br>implicit val optionMonad = new Monad[Option] {<br>  def flatMap[A, B](fa: Option[A])(f: A =&gt; Option[B]): Option[B] = fa.flatMap(f)<br>  def pure[A](a: A): Option[A] = Some(a)<br><br>  @tailrec<br>  def tailRecM[A, B](a: A)(f: A =&gt; Option[Either[A, B]]): Option[B] = f(a) match {<br>    case None              =&gt; None<br>    case Some(Left(nextA)) =&gt; tailRecM(nextA)(f) // continue the recursion<br>    case Some(Right(b))    =&gt; Some(b)            // recursion done<br>  }<br>}</pre><p>In conclusion, I deliberately did not discuss that monad laws as what we have learnt is enough for you kick start your journey to the land of monads! However, Monads is not everything, but having it in your tool box is definitely a thing to work in the functional world of scala.</p><p>Lets take a break from here, but don&#39;t hesitate to buzz me if you don&#39;t understand any aspect of this writeup. Our next discuss will be on the <strong>OptionT </strong>which is also a monad.</p><p><em>If you like this writeup, click the💚 below so more people can see it here on Medium.</em></p><p>Big thanks to @edmundnoble and @TheAlmikey_twitter for reviewing this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b096f33cc153" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Cats library for dummies — part 3]]></title>
            <link>https://medium.com/@abu_nadhr/scala-cats-library-for-dummies-part-3-fd3b185088f0?source=rss-267a344f59a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd3b185088f0</guid>
            <category><![CDATA[cats-library]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[generic-programming]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Idris Kabir]]></dc:creator>
            <pubDate>Mon, 31 Oct 2016 13:38:09 GMT</pubDate>
            <atom:updated>2016-10-31T13:38:09.795Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back to our series of cats library type classes. In this write up we’ll be looking at “<strong>applicative</strong>” , “<strong>semigroup</strong>” and “<strong>monoid</strong>” type classes.</p><h3>Applicative</h3><p>Firstly, the applicative type class is a descendant of the <em>Apply</em> type class we discussed briefly in our previous <a href="https://medium.com/@abu_nadhr/scala-cats-library-for-dummies-part-2-1f2fb31f804c#.ikkkg9rer">article</a>, it basically comes with a function called “pure” which wraps a data type(Int, string, Boolean) into a context (Option, List , Future ). In other terms, it takes a single data type <strong>A</strong> and return a data type <strong>F[A](</strong><em>lifts any value into the </em><strong><em>applicative functor</em>).</strong></p><p>Below is the <a href="https://github.com/typelevel/cats/blob/155f7f534993c30d6e757de990330ac796dad5da/core/src/main/scala/cats/Applicative.scala">signature</a> of the “pure” function.</p><pre>def pure[A](x: A): F[A]</pre><p>Applicative demo</p><pre>scala&gt; import cats._ , cats.implicits._ , cats.instances._<br>import cats._<br>import cats.implicits._<br>import cats.instances._</pre><pre>scala&gt; Applicative[Option].pure(1)<br>res0: Option[Int] = Some(1)</pre><pre>scala&gt; Applicative[List].pure(4)<br>res1: List[Int] = List(4)</pre><h3><strong>Semigroup</strong></h3><p>A <strong>semigroup</strong> is an algebraic structure consisting of a set together with an <a href="https://en.wikipedia.org/wiki/Associative">associative</a> binary operation.</p><p>The cats library semigroup implementation comes with a function “combine” which simply combines 2 values of the same data type(Int, List , string, Option, Map).</p><pre><strong>Associativity is the only principle(law) that the semigroup type class follows. </strong><br>- <strong>(a x b) x c == a x (b x c) == (b x c) x a</strong></pre><p>When we add or multiply a list of variables regardless of their order of arrangement yields the same result.</p><p>Imagine the semigroup combine function like a git merge with on conflicts :)</p><pre>scala&gt; import cats._ , cats.instances._ , cats.implicits._<br>import cats._<br>import cats.instances._<br>import cats.implicits._</pre><pre>scala&gt; 2.combine(3)<br>res0: Int = 5</pre><pre>scala&gt; List(1,3,5).combine(List(1,25,6))<br>res1: List[Int] = List(1, 3, 5, 1, 25, 6)</pre><pre>scala&gt; Option(4).combine(Option(6))<br>res2: Option[Int] = Some(10)</pre><pre>scala&gt; Option(2).combine(None)<br>res3: Option[Int] = Some(2)</pre><p>Remember that writing an express like “2.combine(3)” is possible because we have the implicits functions in scope “cats.implicits._” — cats library have provided a lot of primitive data type implicits readily available for use.</p><p>Semigroup also has a symbolic operator <strong>|+| </strong>which ease typing, I personally like this because its kinda of cleaner!</p><pre>scala&gt; 2 |+| 5<br>res4: Int = 7</pre><pre>scala&gt; List(1,2,4) |+| List(3,5,6)<br>res5: List[Int] = List(1, 2, 4, 3, 5, 6)</pre><pre>scala&gt; Map(&quot;a&quot;-&gt; 1 ) |+| Map(&quot;b&quot;-&gt; 2)<br>res6: Map[String,Int] = Map(b -&gt; 2, a -&gt; 1)</pre><h3>Monoid!</h3><p>Hummmmm……. yet another scary word but is a great tool that can efficiently parallelize computations.</p><p>So what is a monoid ?</p><p>A monoid is an algebraic structure that follows these two basic rules(laws).</p><pre><strong>1. A binary associative operation that takes two values of type <em>A</em> and combines them into one.</strong></pre><pre><strong>2. A value of type <em>A</em> that is an identity for that operation.</strong></pre><p>Lets do a simple arithmetics, when adding 2 integers 3 + 7 we get 10, however, when we add zero(0) to any integer the result will be the same regardless of whether the value zero(0) comes in-front or behind, same applies to multiplication, multiplying an integer with one(1) returns the same result. So therefore we can call <strong>zero(0)</strong> an <em>identity element</em> of addition and <strong>one(1)</strong> an <em>identity element</em> for multiplication.</p><p>With the definition above we can implement the monoid signature.</p><pre>trait Monoid[A]{<br>   def combine(x: A , y: A): A <br>   def empty: A <br>}</pre><pre>#for int addition the monoid will look this</pre><pre>val intAddition = new Monoid[Int]{<br>    def combine(x:Int, y:Int) = x + y <br>    def empty = 0<br>}</pre><pre>#for int multiplication we have </pre><pre>val intMultiplication = new Monoid[Int]{<br>     def combine(x:Int, y:Int) = x*y<br>     def empty = 1 <br>}</pre><pre>#for string concatenation we have </pre><pre>val stringMonoid = new Monoid[String]{<br>    def combine(x:String, y:String) = x + y <br>    def empty = &quot;&quot;<br>}</pre><p>As an exercise you should implement monoid for List, booleanOr and booleanAnd and Options.</p><p>But why monoids ? What do we stand to benefit from monoids ? Well, it turns out that we can write very interesting programs over any data type, knowing nothing about that type other than that it’s a <strong>monoid</strong>.</p><p>Secondly, the fact that a monoid’s operation is associative means that we have a great deal of flexibility in how we fold a data structure like a list, this means that we can split our data into chunks, fold them in parallel , and then combine the chunks with the monoid.</p><p>In the standard scala collections(Sequence, Vectors, Lists , Ranges etc) there exist these methods <em>fold, foldLeft, foldRight</em> — which are used to aggregate values together to return a single value, these methods takes monoids as input parameters.</p><p>Lets try out adding a list of integers using the <strong>intAddition </strong>monoid we defined.</p><pre>scala&gt; import intAddition._<br>import intAddition._</pre><pre>scala&gt; List(1,2,4,5).fold(empty)(combine)<br>res1: Int = 12</pre><pre>scala&gt; import intMultiplication._<br>import intMultiplication._</pre><pre>scala&gt; List(1,2,4,5).fold(empty)(combine)<br>res2: Int = 40</pre><h4>Back to cats implementation of monoid</h4><p>when you add an “<strong>empty</strong>” method(which is equivalent to <em>identity element</em>) to the semigroup <em>combine </em>method we discussed above, you simply get our<strong> monoid</strong>.(hummm, pretty simple!)</p><p>Also, we can find out ourselves that cats library already have predefined the “empty” method for primitive types.</p><pre>scala&gt; Monoid[Int].empty<br>res0: Int = 0</pre><pre>scala&gt; Monoid[Float].empty<br>res1: Float = 0.0</pre><pre>scala&gt; Monoid[String].empty<br>res3: String = &quot;&quot;</pre><p>As stated in the cats documentation - <em>the advantage of using these type class provided methods, rather than the specific ones for each type, is that we can compose monoids to allow us to operate on more complex types.</em></p><pre>Monoid[Map[String,Int]].combineAll(List(Map(&quot;a&quot; -&gt; 1, &quot;b&quot; -&gt; 2), Map(&quot;a&quot; -&gt; 4)))<br>res0: Map[String,Int] = Map(b -&gt; 2, a -&gt; 5)<br></pre><p>Lets take a break from here, our next discuss will be on the <strong>Monad </strong>type class. See you then.</p><p><em>If you like this writeup, click the💚 below so more people can see it here on Medium.</em></p><p>Big thanks to some <strong><em>catlords</em></strong> @fabianmeyer , @mgttlinger and @tkroman for reviewing this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd3b185088f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Cats library for dummies — part 2]]></title>
            <link>https://medium.com/@abu_nadhr/scala-cats-library-for-dummies-part-2-1f2fb31f804c?source=rss-267a344f59a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f2fb31f804c</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[cats-library]]></category>
            <category><![CDATA[generic-programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Idris Kabir]]></dc:creator>
            <pubDate>Tue, 04 Oct 2016 20:02:43 GMT</pubDate>
            <atom:updated>2016-10-04T20:39:10.367Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to part 2 of my cat library for dummies, I encourage you read <a href="https://medium.com/@abu_nadhr/scala-cats-library-for-dummies-part-1-8ec47af7a144">part 1</a> as this is some what a continuation. This article will be centered on the “Apply” type class, remember the “map” function in the Functor type class? its awesomeness was extends to the “Apply” type class too.</p><p>Since Apply extends the <em>Functor type class</em> and the <em>Cartesian type class</em> we pretty much have inherited function like “map” , “compose” e.t.c. However, Apply comes with a special function called “<strong><em>ap</em></strong>” which does something quite unique. It was originally called <em>apply</em>, but later renamed to <em>ap. </em>Below is the <em>ap</em> function signature and an explanation of what is means</p><pre>def <strong>ap</strong>[A, B](ff: F[A =&gt; B])(fa: F[A]): F[B]</pre><pre><strong>(ff: [A =&gt; B] )</strong> — a function that transform a type <strong>F[A</strong> <strong>=&gt; B</strong>]</pre><pre><strong>(fa : F[A])</strong> — a data-type that take only one data-type e.g List, Future , Options</pre><pre><strong>F[B]</strong> — the final return type of the ap function, after applying the <strong>ff</strong> function to the <strong>fa</strong> data-type</pre><p>by carefully looking at the <strong><em>ap</em></strong> signature you will notice two(2) distinct features from the <em>map</em> function in the Functor type class</p><ol><li>the <strong><em>ap</em></strong> transformation function is <strong>F[A =&gt; B]</strong> while in <strong><em>map</em></strong> the transformation function is simply <strong>A =&gt; B</strong></li><li>the parameter list are flipped, in <strong><em>map</em></strong> the data-type variable <strong><em>fa</em> </strong>comes first before the transformation function <strong><em>f </em></strong>whereas in the <strong><em>ap </em></strong>function, the transformation function<strong><em> ff</em></strong> comes first before the data-type variable<strong><em> fa.</em></strong></li></ol><h4>Let have a look that the ap function in action.</h4><pre>scala&gt; import cats._ , cats.instances._ , cats.implicits._<br>import cats._<br>import cats.instances._<br>import cats.implicits._</pre><pre>scala&gt; val addOne : Int =&gt; Int = _ + 1  <br>addOne: Int =&gt; Int = &lt;function1&gt;</pre><pre>scala&gt; Apply[List].ap(List(addOne))(List(1,2,3))<br>res0: List[Int] = List(2, 3, 4)</pre><pre>scala&gt; Apply[Option].ap(Some(addOne))(Some(4))<br>res2: Option[Int] = Some(5)</pre><p>some examples with less typing ;)</p><pre>scala&gt; (addOne).some ap 5.some<br>res3: Option[Int] = Some(6)</pre><pre>scala&gt; (addOne).some ap None<br>res4: Option[Int] = None</pre><pre>scala&gt; List(addOne) ap List(1,2,4)<br>res5: List[Int] = List(2, 3, 5)</pre><p>the examples above applies for only function with a single parameter, what if we want to pass a function(our <strong><em>ff</em></strong> function) that takes 2 , 3 or more parameters ?</p><p>Fortunately, the Apply type class has variant of the <em>ap</em> function which are <em>ap2 , ap3 until ap22.</em></p><p><em>ap2</em> means the <em>ap</em> function takes 2 parameters</p><pre>scala&gt; val addBoth=(a: Int , b: Int) =&gt; a + b <br>addBoth: (Int, Int) =&gt; Int = &lt;function2&gt;</pre><pre>scala&gt; (addBoth).some ap2 (3.some , 5.some)<br>res5: Option[Int] = Some(8)</pre><pre>scala&gt; val append = (a: Int, b: List[Int]) =&gt; a :: b <br>b: (Int, List[Int]) =&gt; List[Int] = &lt;function2&gt;</pre><pre>scala&gt; (append).some ap2 (4.some , List(2,3).some)<br>res8: Option[List[Int]] = Some(List(4, 2, 3))</pre><p>such variants also exist for both<em> map</em> and <em>tuple</em> functions</p><p>map2 , map3 until map22.</p><p>tuple2 , tuple3 until tuple22.</p><h3>The easy path with |@| .</h3><p>When using the higher-arity functions(apN , mapN and tupleN) a neater alternative to use is called the “CartesianBuilder” with a symbol “ |@| ”, let try it out.</p><pre>scala&gt; (5.some |@| 6.some ).map(_ + _ ) <br>res9: Option[Int] = Some(11)</pre><pre>scala&gt;def addOptions( a: Option[Int], b: Option[Int])= (a |@| b).map(_+_)<br>add: (a: Option[Int], b: Option[Int])Option[Int]</pre><pre>scala&gt; addOptions(5.some, 4.some)<br>res10: Option[Int] = Some(9)</pre><pre>scala&gt; addOptions(None, 5.some)<br>res12: Option[Int] = None</pre><p>Same can be applied to List and Future(don&#39;t forget to import the ExecutionContext)</p><pre>scala&gt; import scala.concurrent.Future<br>import scala.concurrent.Future</pre><pre>scala&gt; import scala.concurrent.ExecutionContext.Implicits.global<br>import scala.concurrent.ExecutionContext.Implicits.global</pre><pre>scala&gt; def <strong>ff</strong>(a:Future[Int], b: Future[Int])= (a |@| b).map(_+_)<br>ff: (a: scala.concurrent.Future[Int], b: scala.concurrent.Future[Int])scala.concurrent.Future[Int]</pre><pre>scala&gt; ff(Future.successful(34), Future.successful(56)).foreach(println)</pre><pre>90</pre><p><em>If you liked this writeup, click the💚 below so more people can see it here on Medium</em></p><p>will pulse here for now, hopefully part 3 will be on Applicative and Monad type class.</p><p>Big thanks to <a href="http://twitter.com/julienrf">@julienrf</a> , <a href="http://twitter.com/zainab">@zainab</a>-ali and <a href="http://twitter.com/yilinwei">@yilinwei</a> for taking the time to review this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f2fb31f804c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Cats library for dummies — part 1 .]]></title>
            <link>https://medium.com/@abu_nadhr/scala-cats-library-for-dummies-part-1-8ec47af7a144?source=rss-267a344f59a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ec47af7a144</guid>
            <category><![CDATA[typelevel]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cats]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Idris Kabir]]></dc:creator>
            <pubDate>Tue, 06 Sep 2016 19:57:50 GMT</pubDate>
            <atom:updated>2017-01-13T11:11:44.921Z</atom:updated>
            <content:encoded><![CDATA[<p>The first time I heard about <a href="https://github.com/typelevel/cats">cats</a> library was in a video by the author @d6 in late 2014, quite interesting, I immediately jumped to the website to learn <a href="http://typelevel.org/cats/index.html">more</a>, the first thing that scared me away was the logo (4 cats with 5 directional arrows), I told myself - this library is not for mortals :(</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*VMnH_wQh97iQkpfcG0ouqg.png" /><figcaption>official cat documentation website</figcaption></figure><p>I had no option than to hold on for a while, perhaps things will get clearer in the future, I followed the advise of @kaffeecoder in his <a href="http://danielwestheide.com/blog/2013/04/03/the-neophytes-guide-to-scala-part-16-where-to-go-from-here.html">blog</a> series the-neophytes-guide-to-scala</p><pre> “<em>More often than not, a good way to really get comfortable with a new language and its whole ecosystem of libraries is to use it for </em><strong><em>creating something useful</em>”</strong></pre><p>A started out by building a GPS aggregation application with <a href="https://playframework.com/">playframework,</a> and surprise surprise I needed to do some very basic stuffs like</p><ol><li>Sum up Scala list of Options without multiple mappings.</li><li>Manipulating value inside a future of options.</li><li>Concatenating future of future.</li><li>and many more……….</li></ol><p>These were obviously not very friendly to do in standard Scala, but fortunately the <a href="http://eed3si9n.com/herding-cats/">tutorial on herding cats</a> by <a href="https://twitter.com/eed3si9n">@eed3si9n</a> gave me all I needed to learn cats - <em>that cats library was ONLY a library that followed the category theory principles and I needed not to study category theory before I can use it</em>.</p><p>This greatly helped me to solve the 3 concerns I mentioned above and dive more into the type-level programming.</p><p>Apply, Semigroup, Applicative, Functor, Monoid, Monad — these buzzy words scares object oriented programmers with no background in functional programming(like me). But believe me, they are simply <em>type classes</em> that follows some specific laws.</p><h3>Let start with Functors</h3><p><em>Functors — </em>is a “type class” that have one key function called “<em>map</em>” which is meant for manipulating data types like List[Int] , Option[String] and Futures[Int]<em>( data types of this natural are generically denoted as F[A])</em></p><pre><strong>def</strong> map[A, B](fa: F[A])(f: A =&gt; B): F[B]</pre><p>explanation of the functor map function.</p><pre><strong>(fa : F[A])</strong> — a data-type that take only one data-type e.g List, Future , Options</pre><pre><strong>(f: A =&gt; B )</strong> — a function that transform a type <strong>A</strong> to a type <strong>B</strong> e.g function that takes a string and return an Int. </pre><pre><strong>F[B]</strong> — the final return type of the Functor&#39;s map function e.g if our &quot;<strong>fa</strong>&quot; variable is a List[String] and our &quot;<strong>f</strong>&quot; function is String =&gt; Int , then our map function return type will be a List[Int]</pre><h3>Demo</h3><p>To get started with SBT, simply add the following to your build.sbt file:</p><pre>libraryDependencies += &quot;org.typelevel&quot; %% &quot;cats&quot; % &quot;0.7.2&quot;</pre><p>import cats to your REPL</p><pre>scala&gt; import cats._, cats.instances.all._ <br>import cats._<br>import cats.instances.all._</pre><pre>scala&gt; val len: String =&gt; Int = _.length<br>len: String =&gt; Int = &lt;function1&gt;</pre><pre>scala&gt; Functor[List].map(List(&quot;scala&quot;, &quot;cats&quot;)) (len)<br>res0: List[Int] = List(5,4)</pre><p>Using <a href="http://www.scala-lang.org/api/2.11.8/#scala.util.Either">Either</a> as a Functor</p><p>The standard Either type in Scala does not have a “<em>map</em>” function, however, the cats library defines a Functor instance for it.</p><pre>scala&gt; import cats.syntax.functor._<br>import cats.syntax.functor._</pre><pre>scala&gt; val r: Either[String, Int] = Right(100)<br>r: Either[String,Int] = Right(100)</pre><pre>scala&gt; r.map( x =&gt; x + 1 ) <br>res1: Either[String,Int] = Right(101)</pre><p>One beautiful function inside the cats Functor’s type class I liked some much is the “<em>fproduct</em>” which pairs a value with the result of applying a function to that value.</p><pre>scala&gt; val len: String =&gt; Int = _.length<br>len: String =&gt; Int = &lt;function1&gt;</pre><pre>scala&gt; List(“scala”, “cats”).fproduct(len)<br>res3: List[(String, Int)] = List((scala,5), (cats,4))</pre><p>to make is more readable and useful the result can be converted to a Map collection ;) using toMap</p><pre>scala&gt; res3.toMap<br>res4: scala.collection.immutable.Map[String,Int] = Map(scala -&gt; 5, cats -&gt; 4)</pre><p>There are also more cool functions in the cats <a href="http://typelevel.org/cats/api/#cats.Functor">functor</a> type class that you can try out e.g <em>lift , compose , as.</em></p><p><em>If you like this writeup, click the💚 below so more people can see it here on Medium.</em></p><p><em>Now you can continue on with </em><a href="https://medium.com/@abu_nadhr/scala-cats-library-for-dummies-part-2-1f2fb31f804c#.59exgywr1"><em>part2</em></a><em> </em><a href="https://medium.com/@abu_nadhr/scala-cats-library-for-dummies-part-3-fd3b185088f0#.qarlkqick"><em>,part3</em></a><em> and </em><a href="https://medium.com/@abu_nadhr/scala-cats-library-for-dummies-part-4-b096f33cc153#.8ya5xf9co"><em>part4</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ec47af7a144" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>