<?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 Sanjeev Ranjan on Medium]]></title>
        <description><![CDATA[Stories by Sanjeev Ranjan on Medium]]></description>
        <link>https://medium.com/@sanjeevranjaniitb?source=rss-236ce5c3b133------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6V5BT-9Lo4YtnSc-4yEmwQ.jpeg</url>
            <title>Stories by Sanjeev Ranjan on Medium</title>
            <link>https://medium.com/@sanjeevranjaniitb?source=rss-236ce5c3b133------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:55:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sanjeevranjaniitb/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 FP- Advanced Concepts 2]]></title>
            <link>https://medium.com/@sanjeevranjaniitb/scala-fp-advanced-concepts-2-adfa60e1e72c?source=rss-236ce5c3b133------2</link>
            <guid isPermaLink="false">https://medium.com/p/adfa60e1e72c</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[cats]]></category>
            <dc:creator><![CDATA[Sanjeev Ranjan]]></dc:creator>
            <pubDate>Tue, 14 Jul 2020 17:35:56 GMT</pubDate>
            <atom:updated>2020-07-14T17:35:56.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iH6VJE5di7ARCczLp_qHiA.jpeg" /></figure><p>Folks , i hope you had good time reading my last blog on type classes . If not , I would strongly recommend you to go through it once <a href="https://medium.com/@coolsanjeev1606/scala-fp-advanced-concepts-1-42c0e71eabb4">Scala Type Classes</a> . The goal of this blog are two-fold : to introduce monads , functors , and other functional programming patterns and also guide you through how they are implemented in <a href="https://typelevel.org/cats/">Cats </a>!</p><p>To be honest , these constructs fall under <strong>design patterns in scala</strong> , similar to we have different <a href="https://en.wikipedia.org/wiki/Design_Patterns">design patterns in oops world</a> . The major difference between them are :</p><ol><li>they are formally, and thus precisely, defined</li><li>they are extremely general</li></ol><p>So , lets start . Before diving into Cats Library constructs in scala , lets go into chapters of mathematics for sometime as it has its origin from there . In category theory following are the main constructs you will see again and again .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*z6G9Sgl3g8guX5h8lqyl1Q.png" /></figure><p>Lets peek into them one by one . I will take both mathematical and programmatic approach to demonstrate above concepts and patterns .</p><blockquote><strong>Semigroup</strong></blockquote><p><strong>In mathematics</strong>, a semigroup is an algebraic structure consisting of a set together with an associative binary operation.The binary operation of a semigroup is most often denoted multiplicatively: x·y, or simply xy, denotes the result of applying the semigroup operation to the ordered pair (x, y). Associativity is formally expressed as that (x·y)·z = x·(y·z) for all x, y and z in the semigroup .</p><p><strong>In Scala </strong>, If a type A can form a Semigroup it has an associative binary operation.</p><pre>trait Semigroup[A] {<br>  def combine(x: A, y: A): A<br>}</pre><p>Associativity means the following equality must hold for any choice of x, y, and z</p><pre>combine(x, combine(y, z)) = combine(combine(x, y), z)</pre><p>Examples are quite straight forward and also there is some special syntax as highlighted below :</p><pre>import cats.Semigroup<br><br>implicit val intAdditionSemigroup: Semigroup[Int] = new Semigroup[Int] {<br>  def combine(a: Int, b: Int): Int = a + b<br>}<br>val x = 11<br>val y = 12<br>val z = 31<br>Semigroup[Int].combine(x, y)<br>// res0: Int = 23<br><br>Semigroup[Int].combine(x, Semigroup[Int].combine(y, z))<br>// res1: Int = 54<br><br>Semigroup[Int].combine(Semigroup[Int].combine(x, y), z)<br>// res2: Int = 54</pre><pre>import cats.implicits._<br>1 |+| 2  // <strong>Special Syntax</strong><br>// res3: Int = 3</pre><blockquote><strong>Monoid</strong></blockquote><p><strong>In mathematics</strong>, a monoid is an algebraic structure with a single associative binary operation and an identity element. Monoids are semigroups with identity. Suppose that S is a set and • is some binary operation S × S → S, then S with • is a monoid if it satisfies the following two axioms:</p><p><em>Associativity</em><br>For all a, b and c in S, the equation (a • b) • c = a • (b • c) holds.</p><p><em>Identity element<br></em>There exists an element e in S such that for every element a in S, the equations e • a = a • e = a hold.</p><p><strong>In Scala</strong> , Monoid extends the power of Semigroup by providing an additional empty value</p><pre>trait Semigroup[A] {<br>  def combine(x: A, y: A): A<br>}<br><br>trait Monoid[A] extends Semigroup[A] {<br>  def empty: A<br>}</pre><p>This empty value should be an identity for the combine operation, which means the following equalities hold for any choice of x</p><pre>combine(x, empty) = combine(empty, x) = x</pre><p>Many types that form a Semigroup also form a Monoid, such as Ints (with 0) and Strings (with &quot;&quot;).</p><pre>import cats.Monoid<br><br>implicit val intAdditionMonoid: Monoid[Int] = new Monoid[Int] {<br>  def empty: Int = 0<br>  def combine(x: Int, y: Int): Int = x + y<br>}<br><br>val x = 1<br>Monoid[Int].combine(x, Monoid[Int].empty)<br>// res0: Int = 1<br><br>Monoid[Int].combine(Monoid[Int].empty, x)<br>// res1: Int = 1</pre><blockquote><strong>Functor</strong></blockquote><p><strong>In mathematics</strong>, specifically category theory, a functor is a map between categories. Functors were first considered in algebraic topology, where algebraic objects are associated to topological spaces, and maps between these algebraic objects are associated to continuous maps between spaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AbynCn50_dNuAlbTV0WW6A.png" /></figure><p><strong>In Scala , </strong>Functor is a type class that abstracts over type constructors that can be map‘ed over. Examples of such type constructors are List, Option, and Future.</p><pre>trait Functor[F[_]] {<br>  def map[A, B](fa: F[A])(f: A =&gt; B): F[B]<br>}<br><br>// Example implementation for Option<br>implicit val functorForOption: Functor[Option] = new Functor[Option] {<br>  def map[A, B](fa: Option[A])(f: A =&gt; B): Option[B] = fa match {<br>    case None    =&gt; None<br>    case <em>Some</em>(a) =&gt; <em>Some</em>(f(a))<br>  }<br>}</pre><p>A Functor instance must obey two laws:</p><p><em>Composition </em>: Mapping with f and then again with g is the same as mapping once with the composition of f and g</p><p>fa.map(f).map(g) = fa.map(f.andThen(g))</p><p><em>Identity </em>: Mapping with the identity function is a no-op</p><p>fa.map(x =&gt; x) = fa</p><p>Examples for Functors :</p><pre>import cats.Functor<br>import cats.implicits._</pre><pre>val listOption = <em>List</em>(Some(1), None, Some(2))<br>// listOption: List[Option[Int]] = List(Some(1), None, Some(2))<br><br>// Through Functor#compose<br>Functor[List].compose[Option].map(listOption)(_ + 1)</pre><pre>// res1: List[Option[Int]] = List(Some(2), None, Some(3))</pre><p>Folks , I will cover rest of the topics in subsequent blogs . I would strongly recommend you to practice above examples on your own IDE and play with them a bit . Till the next blog , happy learning !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adfa60e1e72c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala FP- Advanced Concepts 1]]></title>
            <link>https://medium.com/@sanjeevranjaniitb/scala-fp-advanced-concepts-1-42c0e71eabb4?source=rss-236ce5c3b133------2</link>
            <guid isPermaLink="false">https://medium.com/p/42c0e71eabb4</guid>
            <category><![CDATA[type-classe]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[scala-programming]]></category>
            <dc:creator><![CDATA[Sanjeev Ranjan]]></dc:creator>
            <pubDate>Sat, 04 Jul 2020 19:59:13 GMT</pubDate>
            <atom:updated>2020-07-04T19:59:13.905Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*-3CN3ksCEgw5IWalfpIAyg.png" /></figure><p>Folks , hope you are now familiar with scala basics and concepts like <strong>type classes</strong> and <strong>implicits</strong> . Now , in this blog we will leverage these basic concepts to take it to the next level . I would now be covering<strong> type classes</strong> , <strong>cats library</strong> and <strong>for comprehension</strong> in depth with their precise application . Before that , i would recommend you to recap what you have already learnt with below links :</p><ol><li><a href="https://medium.com/@coolsanjeev1606/transition-from-java-oops-to-scala-fp-1-f6802db15f06">Scala FP Blog 1</a></li><li><a href="https://medium.com/@coolsanjeev1606/transition-from-java-oops-to-scala-fp-2-29e11e0e19c1">Scala FP Blog 2</a></li><li><a href="https://medium.com/@coolsanjeev1606/transition-from-java-oops-to-scala-fp-3-54fa45b889d6">Scala FP Blog 3</a></li></ol><blockquote>Type Classes</blockquote><p>So , first advanced feature which you will encounter after implicits in scala is <strong>type classes . Type Classes </strong>are very powerful concepts in scala , they give you power to <strong>add behavior</strong> to any library <strong>without actually changing its code</strong> . Yes , you read it right ! It is sometimes called <strong>ad-hoc inheritance or ad-hoc polymorphism. </strong>Let me explain it in very simple words . Suppose we have following code in a library (The types below are for purpose of converting something(any type) to Json ) .</p><pre>sealed trait Json<br><br>final case class JsString(value: String) extends Json<br><br>final case class JsInteger(value: Int) extends Json<br><br>final case class JsDouble(value: Double) extends Json<br><br>final case class JsObject(get: Map[String, Json]) extends Json<br><br>case object JsNull extends Json</pre><p>Now we create something called a <strong>type class</strong> , which is a very generic trait that will work for all types as :</p><pre>trait JsonWriter[A] {<br>  def write(value: A): Json<br>}</pre><p>A is a generic type , so you can use a Person or any other class as well . So, with above two stuffs in library , you can actually write Json Converter for any type . Lets define a class Person and try writing its Converter .</p><pre>final case class Person(name: String, email: String)</pre><p>we will have to define instances of type class as below :</p><pre>object JsonWriterInstances {<br>  implicit val <em>stringWriter</em>: JsonWriter[String] =<br>    new JsonWriter[String] {<br>      def write(value: String): Json =<br>        <em>JsString</em>(value)<br>    }<br>  implicit val <em>personWriter</em>: JsonWriter[Person] =<br>    new JsonWriter[Person] {<br>      def write(value: Person): Json =<br>        <em>JsObject</em>(<em>Map</em>(<br>          &quot;name&quot; -&gt; <em>JsString</em>(value.name),<br>          &quot;email&quot; -&gt; <em>JsString</em>(value.email)<br>        ))<br>    }<br><br>  implicit def optionWriter[A](implicit writer: JsonWriter[A]): JsonWriter[Option[A]] =<br>    new JsonWriter[Option[A]] {<br>      def write(option: Option[A]): Json =<br>        option match {<br>          case <em>Some</em>(aValue) =&gt; writer.write(aValue)<br>          case None =&gt; JsNull<br>        }<br>    }<br>}</pre><p>Now , with above instances in context we can make below example work</p><pre>object JsonSyntax {<br><br>  implicit class JsonWriterOps[A](value: A) {<br>    def toJson(implicit w: JsonWriter[A]): Json =<br>      w.write(value)<br>  }<br>}<br><br>object tester2 extends App {<br><br>  import JsonSyntax._<br>  import JsonWriterInstances._<br><br>  <em>println</em>(<em>Option</em>(<em>Person</em>(&quot;Dave&quot;, &quot;sanjeev@example.com&quot;)).toJson)<br>}</pre><pre><strong>O/p:</strong></pre><pre>JsObject(Map(name -&gt; JsString(Dave), email -&gt; JsString(sanjeev<a href="/service/mailto:dave@example.com">@example.com</a>)))</pre><p>Now , let me explain you how the things are working point by point :-</p><ol><li>We have an API exposed to user <strong>toJson . </strong>That is expected to convert any type’s instance to Json .</li><li>As you can observe above method is in <strong>JsonWriterOps </strong>implicit class that takes a very generic type A .</li><li>We just had to write the<strong> implicit type-class instances (<em>stringWriter ,personWriter , </em>optionWriter </strong>)and import it in context to <strong>make toJson API work for any type , </strong>amazing feature ..isn’t !</li></ol><p>I will take a pause here and cover cats library and its type classes in next section . Till then happy learning :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42c0e71eabb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transition from java OOPs to scala FP-3]]></title>
            <link>https://medium.com/@sanjeevranjaniitb/transition-from-java-oops-to-scala-fp-3-54fa45b889d6?source=rss-236ce5c3b133------2</link>
            <guid isPermaLink="false">https://medium.com/p/54fa45b889d6</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[cats]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Sanjeev Ranjan]]></dc:creator>
            <pubDate>Sun, 07 Jun 2020 22:07:02 GMT</pubDate>
            <atom:updated>2020-06-07T22:48:37.024Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*-3CN3ksCEgw5IWalfpIAyg.png" /></figure><p>Folks , I hope you had fun time contending functions as <strong>pure or impure</strong> ones in context to my previous blog . If not , i will get into its depth in a while and give you enough reasons why you should adhere to <strong>pure functions</strong> as far as possible .</p><p>If you haven&#39;t browsed yet ,i would strongly recommend you to peek through the contents shared in my previous two blogs , links below :</p><ol><li><a href="https://medium.com/@coolsanjeev1606/transition-from-java-oops-to-scala-fp-1-f6802db15f06">Java OOPs to Scala FP : Transition 1</a></li><li><a href="https://medium.com/@coolsanjeev1606/transition-from-java-oops-to-scala-fp-2-29e11e0e19c1">Java OOPs to Scala FP : Transition 2</a></li></ol><p>Following are some of the arguments , why i would prefer pure functions over impure ones :</p><ol><li>Function signature says everything about the function i.e. they are easier to reason about .</li><li>They are easy to compose .</li></ol><pre>val composedFunction= function1(a).function2(b).function3(c)                </pre><p>3. They are easier to test and debug .</p><p>4. They can easily be used in parallel programming .</p><p>There are plenteous number of positive arguments about why one should go for <em>pure functional programming paradigm </em>avoiding any side-effects . But , it is not always feasible to write and compose pure functions and avoid side-effects. You will have to deal with side-effects at some place in your code . To reduce side-effects(<em>mostly IOs</em>) and make programs more functional , we would be using some of the <a href="https://wiki.haskell.org/Category_theory"><strong>category theory</strong></a> constructs known as <strong><em>Functors</em></strong><em> , </em><strong><em>Monads</em></strong><em> , </em><strong><em>State Monads</em></strong> ,<em> </em><strong><em>IO Monads</em></strong> and others .You don’t need to worry about them as of now , as i will cover all of them in great depth in my series.</p><p>In my previous blog , i shared a list of topics and grouped them in a sequence i would be covering them . Let us continue from there . We already covered basics of functions and their representations , now let us peek into implicits .</p><h3><strong><em>Scala Implicits</em></strong></h3><p>When we enter into the world of <em>Scala as a beginner</em>, we experience tough time understanding and using implicits . Let me demystify them quickly for you. Some people talk of them in terms of dependency injection , but they are just <strong>context values , </strong>you would always need to do your computing . e.g.</p><pre>def demoImplicits(param: String = &quot;Hello&quot;)(implicit name: String): String = <br>{<br>  s&quot;<strong>$</strong>{param} your implicit parameter is <strong>$</strong>{name}&quot;<br>}<br>implicit val str=&quot;implicit value&quot;<br>demoImplicits()</pre><pre><strong>O/P in Scala REPL :</strong></pre><pre>demoImplicits: (param: String)(implicit name: String)String</pre><pre>str: String = implicit value</pre><pre>res8: String = Hello your implicit parameter is implicit value</pre><p>You might have guessed what is happening in the code above .We have a function <strong>demoImplicits</strong> that takes two parameters one is implicit and one is normal . You will have to <strong>present the implicit parameter in the context</strong> of execution to run the program successfully . So, if the scala compiler is not able to find one , you will get an error .Also , if you have more than one implicit defined in the context then you will get ambiguous implicit error .</p><p>I will list down some important points in respect to scala implicits :</p><ol><li>Implicits can be in many forms : parameters as shown above , implicit classes (providing helper methods for types ) and type classes .Examples below :</li></ol><p><strong>Implicit class :</strong></p><pre>object StringHelper {<br>  implicit class StringOps(str: String) {<br>    def toUC = str.toUpperCase() + &quot;!&quot;<br>    def isQn = str.endsWith(&quot;?&quot;)<br>  }<br>}<br>import StringHelper._<br>&quot;Hello world&quot;.toUC <br>&quot;How are you?&quot;.isQn</pre><pre><strong>O/P in Scala REPL :</strong></pre><pre>defined object Helpers</pre><pre>import Helpers._<br>res0: String = HELLO WORLD!<br>res1: Boolean = true</pre><p>you can observe how <strong>toUC</strong> and <strong>isQn</strong> are acting as methods on string instances as they were methods inside String API but they aren’t !</p><p><strong>Type class implicits :</strong></p><pre>def sum[A: Monoid](values: Seq[A]): A = {<br>  val ev = <em>implicitly</em>[Monoid[A]]<br>  values.foldLeft(ev.zero)(ev.plus)<br>}</pre><p>P.S. implicitly is just a regular function in Predef.scala that basically takes a single implicit parameter, gives it a name and returns it. Looks like this:</p><pre>def implicitly[T](implicit e: T) = e</pre><p>Implicits in scala are powerful tools of the language which can be used in different context to achieve different goals. Comes without saying that because of it’s non explicit nature its easy to get things wrong so use it carefully .</p><p>2. Implicits are searched by scala compiler ! The corrected implicit parameter precedence to remember are :</p><ul><li>implicits visible to current invocation scope via local declaration, imports, outer scope, inheritance, package object that are accessible without prefix.</li><li><em>implicit scope</em>, which contains all sort of companion objects and package object that bear some relation to the implicit’s type which we search for (i.e. package object of the type, companion object of the type itself, of its type constructor if any, of its parameters if any, and also of its supertype and supertraits).</li></ul><p>If at either stage we find more than one implicit, static overloading rule is used to resolve it.</p><h3>Scala Building Blocks</h3><p>I want to give refresher highlights for the basic building blocks in scala to enlighten your memory again ! . Following are the built in types in scala with inheritance diagram :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*4gScBulmISC8mWemaT9eSg.jpeg" /></figure><p>So , Any is the super class of everything just like object class in java and rest all is obvious from the above visual . Next are Classes , Case Classes , Traits and Objects . Lets look into them one by one quickly .</p><ol><li><strong>Scala Classes :</strong></li></ol><p>Scala class is a user-defined blueprint or prototype from which objects are created. Or in other words, a class combines the fields and methods(member function which defines actions) into a single unit. Basically, in a class constructor is used for initializing new objects, fields are variables that provide the state of the class and its objects, and methods are used to implement the behavior of the class and its objects. Syntax to declare a class in scala is as follows :</p><pre>class Greetor extends Actor{<br>  def receive={<br>    case <em>WhoToGreet</em>(who) =&gt; <em>println</em>(s&quot;hello <strong>$</strong>who&quot;)<br>  }<br>}</pre><p><strong>2 . Scala Objects</strong></p><p>Scala is more object-oriented than Java because in Scala, we cannot have static members. Instead, Scala has <strong>singleton objects</strong>. A singleton is a class that can have only one instance, i.e., Object. You create singleton using the keyword <strong>object</strong> instead of class keyword. Since you can’t instantiate a singleton object, you can’t pass parameters to the primary constructor. You already have seen all the examples using singleton objects where you called Scala’s main method. Syntax of Object in scala is as follows :</p><pre>object HelloWorld extends App {<br>  def print: String = &quot;Hello Functional Programming ...&quot;<br>   <em>print<br></em>}</pre><p><strong>3. Case Classes and Case Objects</strong></p><p>Scala case classes are just regular classes which are immutable by default and support extraction through pattern matching.It uses equals method to compare instance . It does not use new keyword to instantiate object.All the parameters listed in the case class are public and immutable by default.A case class generates an object with apply method as default . This apply gets called on instance creation which acts as syntactic sugar .</p><pre>sealed trait Json // Traits explained below <br><br>final case class JsString(value: String) extends Json<br><br>final case class JsInteger(value: Int) extends Json<br><br>final case class JsDouble(value: Double) extends Json<br><br>final case class JsObject(get: Map[String, Json]) extends Json<br><br>case object JsNull extends Json</pre><p><strong>4. Traits</strong></p><p>Traits are used to share interfaces and fields between classes. They are similar to Java 8’s interfaces. Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.Traits become especially useful as generic types and with abstract methods. Following is a simple example to demonstrate traits in practice :</p><pre>trait Iterator[A] {<br>  def hasNext: Boolean<br>  def next(): A<br>}</pre><pre>class IntIterator(to: Int) extends Iterator[Int] {<br>  private var <em>current </em>= 0<br>  override def hasNext: Boolean = <em>current </em>&lt; to<br>  override def next(): Int = {<br>    if (hasNext) {<br>      val t = <em>current<br>      current </em>+= 1<br>      t<br>    } else 0<br>  }<br>}<br><br><br>val iterator = new IntIterator(10)<br>iterator.next()  // output is 0<br>iterator.next()  // output is 1</pre><p>That ends the scala building blocks ! Would be sharing further notes in the next part of the series . Till then happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54fa45b889d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transition from java OOPs to scala FP -2]]></title>
            <link>https://medium.com/@sanjeevranjaniitb/transition-from-java-oops-to-scala-fp-2-29e11e0e19c1?source=rss-236ce5c3b133------2</link>
            <guid isPermaLink="false">https://medium.com/p/29e11e0e19c1</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[cats]]></category>
            <category><![CDATA[scala-advanced]]></category>
            <category><![CDATA[scala-programming]]></category>
            <category><![CDATA[scala-for-java-developers]]></category>
            <dc:creator><![CDATA[Sanjeev Ranjan]]></dc:creator>
            <pubDate>Wed, 27 May 2020 20:27:55 GMT</pubDate>
            <atom:updated>2020-06-12T12:36:08.197Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*ZNjX7UdK7T7_5mbwCn0diQ.png" /></figure><p>Welcome to part 2 of the series . As promised , I am back again with continued story of my transition from java to scala . Believe me , I don’t want anyone to go through the same long painful journey which i did during learning of this niche paradigm of programming . I want to simplify your life to such an extent that you understand FP to the max and you are well versed to read / understand any Scala code and make required changes to it or <strong>write your own ones</strong> .If you haven’t already gone through my introduction blog , i would strongly recommend you to do so. Link here:</p><blockquote><a href="https://medium.com/@coolsanjeev1606/transition-from-java-oops-to-scala-fp-1-f6802db15f06"><em>java OOPs to Scala FP : Transition 1</em></a></blockquote><p>For convenience , i have tried to broadly classify the topics into following sections :</p><ol><li>Introduction to functions ,different ways of representing them and <em>implicits .</em></li><li>Designing your own system in Scala ( would constitute the building blocks like <em>case classes , traits , anonymous functions and others </em>) .</li><li><em>Currying</em> , <em>Partial Functions</em> and <em>Higher Order Functions .</em></li><li><em>Scala collections </em>: Use cases and advanced features .</li><li><em>Recursion .</em></li><li><em>Cats Library :why , when , which and how to use it </em>( Would include Monoids , Functors , Monads , M Transformers , different flavors of monads in cats library) .</li><li><em>Asynchronous</em> and <em>synchronous</em> processing in Scala .</li></ol><p>Without wasting much of time , lets begin with these inspiring words :</p><blockquote><strong>“ The beginning is the most important part of the work.”</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*ZvyvKprkIQQZDgGS0J_Nzw.png" /></figure><h4><strong><em>Functions :</em></strong></h4><p>Functions are the first class citizens in FP (Functional Programming , i would be using FP in most of my talks) . In FP they are just like<strong> algebraic functions</strong> . If you have a little bit knowledge of <strong>set theory</strong> or what<strong> mapping</strong> means you would easily understand what a function is .</p><p><em>In mathematics</em> , y=f(x) would mean y is a function of x . This implies y can be any thing that varies over x for e.g<strong><em> y=2x i.e y=2*x (Double function) . </em></strong><em>Implied , if you have value of x as 2 the value of y would be 4 and so on ..</em></p><p><em>Similarly</em> , In <strong>scala</strong> a function (pure function , i would come to it in a while ) is a mapping of <strong>Input =&gt; Output</strong> i.e for any input , we should have an output that doesn&#39;t change for a fixed input.So, the same <strong>Double function</strong> above in <strong>mathematics</strong> would look like below in <strong>scala</strong> :</p><pre>def double(value: Int): Int = {<br>  value * 2<br>}</pre><p>I won’t guide you through scala syntax , as i assume you are are familiar with basics of it . Some properties can be noted down for the above function :</p><ol><li>It is very much similar to the algebraic function <em>y=f(x)=x*2</em> as both doubles the input value .<strong><em>{scala pure functions have algebraic behavior }</em></strong></li><li>Input and Output values are deterministic i.e for a fixed input you will always get a fixed output .<strong><em>{Known range of values for a known domain}</em></strong></li><li>there is no talking to external world ,i.e. it just cares about its input and doubles it ,which is its output . <strong><em>{ referred as it has No Side Effects }</em></strong></li><li>We can substitute value of the function with their corresponding values i.e double(5) can be substituted by 10 . <strong><em>{Known as Referential Transparency}</em></strong></li></ol><p>So folks , all functions in scala that have above four properties are called as <strong>pure functions . </strong><em>In our discussion we would mostly stick to pure functions unless we are bound to use impure ones</em><strong> . </strong>There is one more way you can represent this double function i.e</p><pre>val double = (value: Int) =&gt; 2 * value</pre><p>This is known as anonymous function way . call it by <strong>double(16)</strong> .Just to clarify the above function is an instance of type <strong>Function1</strong> which takes in one input and returns single output .</p><p>With that said , I would like to take a pause here and expect y&#39;all to play around with above concepts . See if you can reason about your functions as pure ones , if not why ? can you make them pure somehow ? . hmm , i know you will ask why do i care about making them pure if my task is getting done !— Well the answer is not single lined . I would get back with all your impatient queries in the next part of the series . Till then enjoy this quote from Masterminds of Programming , by Federico Biancuzzi -:)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*kh3N_vF9MBB5DRuawXQqMg.png" /></figure><blockquote><a href="https://medium.com/@coolsanjeev1606/transition-from-java-oops-to-scala-fp-3-54fa45b889d6">Link for Part 3</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29e11e0e19c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transition from java OOPs to scala FP -1]]></title>
            <link>https://medium.com/@sanjeevranjaniitb/transition-from-java-oops-to-scala-fp-1-f6802db15f06?source=rss-236ce5c3b133------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6802db15f06</guid>
            <category><![CDATA[scala-programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[scala-advanced]]></category>
            <category><![CDATA[cats]]></category>
            <category><![CDATA[scala-for-java-developers]]></category>
            <dc:creator><![CDATA[Sanjeev Ranjan]]></dc:creator>
            <pubDate>Mon, 25 May 2020 17:53:38 GMT</pubDate>
            <atom:updated>2020-05-27T21:49:59.168Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*NwZiIRtgpN_AyRqRM1HXDQ.png" /></figure><p>My journey has been a roller-coaster ride and is worth mentioning here for the programmers who are looking how to gain that extra bit of confidence in this ever-changing habitat and perform remarkably well .From a guy who started writing pretty much <em>verbose</em> code in start of the career to writing very much neat and pleasant ones , the journey has been prodigious .I will write the whole transition of mine in a series of articles demonstrating Einsteins famous quote which encourages all.</p><p><strong>“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”</strong></p><p>To start with i want to explicate that this article is not a debate between languages or proving out any specific point but in support to general theory to evolve for survival of the fittest . In these series of articles , i would basically guide you through the complete pathway of scala and advanced . I myself started up with very basic building blocks and now i can understand almost any type of scala code . So to start with let’s have a glimpse of comparison which i started off .</p><p>Snippet of early days in java .. the evergreen quick-sort algorithm in java :</p><pre>class QuickSortJava {<br><br>    int partition(int arr[], int low, int high) {<br>        int pivot = arr[high];<br>        int i = (low - 1);<br>        for (int j = low; j &lt; high; j++) {<br>            if (arr[j] &lt; pivot) {<br>                i++;<br>                int temp = arr[i];<br>                arr[i] = arr[j];<br>                arr[j] = temp;<br>            }<br>        }<br>        int temp = arr[i + 1];<br>        arr[i + 1] = arr[high];<br>        arr[high] = temp;<br><br>        return i + 1;<br>    }<br><br>    void sort(int arr[], int low, int high) {<br>        if (low &lt; high) {<br>            int pi = partition(arr, low, high);<br>            sort(arr, low, pi - 1);<br>            sort(arr, pi + 1, high);<br>        }<br>    }<br><br>    static void printArray(int arr[]) {<br>        int n = arr.length;<br>        for (int i = 0; i &lt; n; ++i)<br>            System.<em>out</em>.print(arr[i] + &quot; &quot;);<br>        System.<em>out</em>.println();<br>    }<br><br>    public static void main(String args[]) {<br>        int arr[] = {10, 7, 8, 9, 1, 5};<br>        int n = arr.length;<br>        QuickSortJava ob = new QuickSortJava();<br>        ob.sort(arr, 0, n - 1);<br>        System.<em>out</em>.println(&quot;sorted array&quot;);<br>        <em>printArray</em>(arr);<br>    }<br>}</pre><p>Below is the scala version of the same quick-sort algorithm . Doesn’t it looks more like English which is easily readable and understandable ?</p><pre>object QuickSort extends App{<br>  <em>println</em>(<em>quicksort</em>(<em>List</em>(6, 9, 23, 1, 2, 3)))<br><br>  def quicksort(xs: List[Int]): List[Int] = {<br>    xs match {<br>      case <em>Nil </em>=&gt; <em>Nil<br>      </em>case head :: tail =&gt; {<br>        val (low, high) = tail.partition(_ &lt; head)<br>        <em>quicksort</em>(low) ::: head :: <em>quicksort</em>(high)<br>      }<br>    }<br>  }<br>}</pre><p>it is not only pearls of code in both the JVM languages , but also it gives you a lot many things to ponder upon while solving a computer problem .Following are some :</p><ol><li>How efficient is my code ?</li><li>How neat is my code ?</li><li>How maintainable is my code ?</li><li>what is the effort required to do a task in your habitat?</li><li>What is the learning curve for the environment and the language ?</li></ol><p>So, next i would be starting up with a contrast discussion of scala with respect to java . I will make sure you understand every component of FP in scala and finally demystify some of the abstraction level libraries like cats , scalaz and others . To have an objective in mind , this series is for someone who feels confused reading about monads ,functors ,state monads , IO and other advanced scala topics , who doesn’t has much confidence in writing code like</p><pre>def updateHealth (delta: Int): Game[Int] =<br>         StateT[IO, GameState, Int] {<br>            (s: GameState) =&gt;<br>             val newHealth = s.player.health + delta<br>               IO ((s.copy (player = <br>      s.player.copy (health = newHealth) ), newHealth) )<br>}</pre><p>So , stay tuned for more …..</p><p>Link for part 2 :</p><blockquote><a href="https://medium.com/@coolsanjeev1606/transition-from-java-oops-to-scala-fp-2-29e11e0e19c1">https://medium.com/@coolsanjeev1606/transition-from-java-oops-to-scala-fp-2-29e11e0e19c1</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6802db15f06" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>