<?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 Gábor Manner on Medium]]></title>
        <description><![CDATA[Stories by Gábor Manner on Medium]]></description>
        <link>https://medium.com/@kartonfarkas?source=rss-5df1c09b5f4b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1hcRVSOZMU9jcf_PW6_52A.jpeg</url>
            <title>Stories by Gábor Manner on Medium</title>
            <link>https://medium.com/@kartonfarkas?source=rss-5df1c09b5f4b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 14:57:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kartonfarkas/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[Monads!]]></title>
            <link>https://medium.com/emarsys-craftlab/monads-12f3ffcbb629?source=rss-5df1c09b5f4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/12f3ffcbb629</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[emarsys-dev]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Gábor Manner]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 11:07:32 GMT</pubDate>
            <atom:updated>2024-06-18T11:07:32.927Z</atom:updated>
            <content:encoded><![CDATA[<p>FP is Fun and Practical 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1CB3EJYQ5rmgSpwqhG2Dw.png" /></figure><h3>Monads are coming!</h3><p>You are tasting Functional Programming, and you see it’s good, it has a nice descriptive syntax, you like its expressiveness. However, you still find it a bit exotic (which can also be good), you start thinking that you are getting to understand it.</p><p>Then you bump against something strange and fearful: Monads!</p><p>So your friend comes and tries to help you and explains they are not some scary barbarians or sci-fi monsters who are galloping to you to bite your head off.</p><p>This is when you realize: they are even worse! Some mathematical things! And it is all about category theory and other mystical stuff.</p><p>Of course if you are more of a math-guy it can be rather comforting. Then you can go on… My mission is completed here.</p><p>Otherwise, stay with me, I try to introduce you to each other.</p><h3>The power of Monads</h3><p>Monads are a powerful and fundamental concept in functional programming, but they can also be a source of confusion and fear for many developers. Some people even believe that monads are inherently complicated and only for mathematicians or experts in category theory.</p><p>However, the truth is that monads are actually quite simple once you understand the basic concepts behind them. At their core, monads are just a way of structuring computations that have side effects or that need to carry state throughout the computation. In fact, you’ve probably already used monads in some form without even realizing it. You will be surprised!</p><p>I think there is a switch in your mind somewhere, which turns over at some point of understanding. And then you learn to stop worrying and love the Monads.</p><p>I’d like to help you find that switch.</p><h3>How to learn to love them?</h3><p>When it comes to learning a complex concept like monads in functional programming, there are often two types of people with different learning styles and approaches.</p><p>The first group consists of people who want to fully understand a topic before using it. These individuals are often more theoretical in their approach and like to dive deep into the underlying concepts and principles before they feel comfortable applying them. They may prefer to read books, attend lectures to gain a solid understanding of monads before they start using them in their code.</p><p><em>For this group, an examination of Category Theory would be worthwhile. I would particularly suggest reading Bartosz Milewski’s: </em><a href="https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/"><em>Category Theory for Programmers</em></a><em>, which I find to be an excellent resource. This is a series of blog posts that provides a gentle introduction to category theory, with a focus on its applications in computer science.</em></p><p><em>Or if you prefer watching videos, check this out: </em><a href="https://www.youtube.com/watch?v=yAi3XWCBkDo"><em>A Sensible Introduction to Category Theory</em></a><em>. It is a very great one as well.</em></p><p><em>Then if you like, get back to this article.</em></p><p>The second group consists of people who are more empiric in their approach. These individuals prefer to see how things work in practice and experiment with them to gain a better understanding. They may be more comfortable jumping right into code and using monads in real-world scenarios to see how they behave and how they can be applied. Then they dig deeper to connect the dots between the practical application and the underlying theory.</p><p>I think I will favor more for the second group with my examples, but first I still need to lay some foundations.</p><h3>What is a Monad?</h3><p>A monad is a design pattern that helps us handle computations in a structured and composable way. It is essentially a container type that provides a way to chain together operations that return the same type of container. The beauty of monads is that they provide a uniform interface for working with different types of containers, making it easy to write generic code that works with any monad.</p><p>The monad concept in functional programming is rooted in category theory.</p><p>Category theory is a branch of mathematics that studies the properties of structures and relationships between different mathematical structures. In category theory, a category is a collection of objects and morphisms between them that satisfy certain axioms.</p><p>One of the fundamental elements of category theory is the functor. Let’s see what it is.</p><h3>Functor</h3><p>Functor is a mapping between categories that preserves the structure of the categories. In the context of programming, a functor is a type constructor that defines how to map functions over the values of a type. Functors provide a way of abstracting over container-like data types such as lists, trees, and maps. In functional programming, functors are used to lift functions from operating on simple values to operating on values within a context, such as a container.</p><p>Does it ring any bells to you? Yes, we’ve done such a thing before!</p><pre>val maybeString: Option[String] = Some(&quot;It is a molehill&quot;)</pre><pre>maybeString.map(_.replace(&quot;molehill&quot;, &quot;mountain&quot;))</pre><pre>// this is how we make a mountain out of a molehill</pre><p>So here we use map to lift our replace function to operate on our value (our String) within its context: the Option .</p><p>The main method of Functor is map, which takes a function A =&gt; B and a functor-wrapped value F[A] and applies the function to the value, returning a functor-wrapped result F[B].</p><p>Here we mapped our String to another String, but as the signature (map[B](f: A =&gt; B): F[B] ) tells us, you can map your value to another type.</p><pre>val stringNumber: Option[String] = Some(&quot;42&quot;)</pre><pre>val intNumber: Option[Int] = stringNumber.map(_.toInt)</pre><p>And here we are! Yep, you guessed right, our belovedOption is a functor!</p><h3>Monad</h3><p>As we are already not afraid of functors from now on, we can take another step into the cave and meet the monads as they are just one bit more scary than functors.</p><p>A monad is a type of functor that provides a way to sequence computations that are wrapped in a context. In other words, it provides a way to chain together computations that may have side effects or may depend on previous computations.</p><p>Basically we use monads to encapsulate the state changes, side effects to protect our pure, stateless and effectless code from them.</p><p>The key concept of monads is that they provide two operations:</p><ul><li><strong>bind: </strong>also known asflatMap<strong> </strong>in Scala and &gt;&gt;= in Haskell</li><li><strong>identity</strong>: unit or pure in Scala and return in Haskell</li></ul><p>The bind operation allows us to chain together operations that return a monad. The identity operation takes a non-monadic value and wraps it in a monad.</p><h3>Monads are burritos!</h3><p>There is a metaphor often mentioned for monads: Monads are burritos! As I know this started as a parody for (monad) tutorials here:</p><p><a href="https://byorgey.wordpress.com/2009/01/12/abstraction-intuition-and-the-monad-tutorial-fallacy/">Abstraction, intuition, and the &quot;monad tutorial fallacy&quot;</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*Gc59Ntl1mG1D2GqL.jpg" /></figure><p>Later it started to spread in the functional programming community as a meme until someone found its “hidden meaning” and it indeed became a real analogy (but still some kind of joke):</p><p><a href="https://blog.plover.com/prog/burritos.html">The Universe of Discourse : Monads are like burritos</a></p><p>I hope I haven’t already fallen in the monad tutorial fallacy with my article, but as I find this analogy expressive (although it is very divisive in the community) for some particular attributes of monads, I’m upping the stakes and say that identitywraps your goodies into the tortilla and bind makes you able to reach the fillings inside.</p><p>And it is generally easier to handle all your delicious ingredients wrapped into a tortilla — when you are eating it by your bare hands -, than messing around with them in their own.</p><h3>Make some burritos</h3><p>And burritos are best with friends.</p><p>I was struggling to come up with a great practical yet simple example using Monads. Then just remembered that <a href="https://medium.com/@dani3l.balazs">Dániel Balázs</a> — one of my dearest colleagues, who likes burritos very much — has written an excellent article about <em>Tagless Final</em> and how it aids the Least Power Principle: <a href="https://blog.craftlab.hu/tagless-final-from-a-different-perspective-72321a29bbe3">Tagless final — from a different perspective</a>.</p><p><em>Tagless Final is a pattern to abstract away the dependencies of our code. It is often used in conjunction with monads since monads provide a way to abstract over effectful computations (eg. writing to a database).</em></p><p>I think this article will be a useful reading material later on our journey into FP, and it even uses the holy <strong>IO monads</strong> provided by the famous library <strong>cats</strong> (beware, the above one, which is trapped in a burrito is not one of them)!</p><p>So I was thinking to borrow his examples about modifying account balances, as I find them practical and descriptive. But I didn’t want to introduce some fancy monads for now.</p><p>So for the sake of simplicity and burritos I would stay in the kitchen, and just use Options as monads while we are getting acquainted to the basics.</p><p>Let’s say we have different containers: a fridge and a shelf where we store the stuff and a tortilla, in which we would like to mix some ingredients.</p><pre>import scala.collection.mutable.ListBuffer</pre><pre>case class Container(name: String, content: ListBuffer[String])</pre><pre>object Kitchen {<br>  val containers: ListBuffer[Container] = ListBuffer(<br>    Container(&quot;shelf&quot;, ListBuffer(&quot;beans&quot;, &quot;flour&quot;, &quot;rice&quot;)),<br>    Container(&quot;fridge&quot;, ListBuffer(&quot;tomato&quot;, &quot;beef&quot;, &quot;onion&quot;)),<br>    Container(&quot;tortilla&quot;, ListBuffer())<br>  )<br>}</pre><p><em>Generally we like to avoid mutable types (especially when we are dealing with multiple threads), like ListBuffer, I’ve just used it here for simplicity again.</em></p><p>Even a simple task like getting a tomato from the fridge and putting it into a tortilla requires to handle a lot of things and we have to meet several conditions:</p><ol><li>there should be a fridge</li><li>where there should be a tomato</li><li>we should have a tortilla</li></ol><p>(and of course motor and other skills as well).</p><p>Even if only one of them fails, this procedure couldn’t end up with a tomato in our tortilla.</p><p>So wee see our success depends on the absence of our goods. So our <em>effect</em> is their existence. Oh, yeah! That’s an Option!</p><p>We can achieve our goals using (<em>if</em>) conditions, but as we learned how to map Optionin the previous article, let’s do it like that:</p><pre>Kitchen.containers.find(_.name == &quot;fridge&quot;).map { fridge =&gt;<br>  fridge.content.find(_ == &quot;tomato&quot;).map{ tomato =&gt;<br>    Kitchen.containers.find(_.name == &quot;tortilla&quot;).map { tortilla =&gt;<br>      tortilla.content += tomato<br>      fridge.content -= tomato<br>      tomato<br>    }<br>  }<br>}</pre><p>So we get the fridge, if it is there we pick the tomato from it, then if (we have) we put it in our tortilla (so we programatically remove it from the fridge and add it to the tortilla). And we get our tomato (in the tortilla):</p><pre>val res0: Option[Option[Option[String]]] = Some(Some(Some(tomato)))</pre><p>Holy Macaroni!</p><p>To be more exact: we get some tomato which is in something that is in another something…</p><p>And in the case we don’t have a tomato (or we try to get another one from the fridge) we get:</p><pre>val res0: Option[Option[String]] = Some(None)</pre><p>Great! In Hungarian we have a proverb “Nesze semmi, fogd meg jól!” which translates something like “Take this nothing, and hold it tight!”. Thanks!</p><p>And what’s more, if we don’t have any tortilla:</p><pre>val res0: Option[Option[Option[String]]] = Some(Some(None))</pre><p>Yikes! I don’t want to deal with those substances! I just want my tomato — or nothing…</p><p>What we have done is that we unwrapped our elements (from their existence) one after one, then we wrapped them back again carefully. But we also have flatMapwhich can do this wrappings for us and we can deal with only the very thing we basically want to deal with. This time, the beef!</p><pre>Kitchen.containers.find(_.name == &quot;fridge&quot;).flatMap { fridge =&gt;<br>  fridge.content.find(_ == &quot;beef&quot;).flatMap { lettuce =&gt;<br>    Kitchen.containers.find(_.name == &quot;tortilla&quot;).map { tortilla =&gt;<br>      tortilla.content += lettuce<br>      fridge.content -= lettuce<br>      lettuce<br>    }<br>  }<br>}</pre><p>So here flatMap goes across the existence of the fridge and the tortilla, and gets us the beef directly (in its own existence):</p><pre>val res1: Option[String] = Some(beef)</pre><p>So it chains (composes) all the elements through their wrappings (their existence, ie. Option) and lets us reach (apply our action) on the very inner item. If any of them doesn’t exist, we get a simple None(a non-existing beef).</p><p>Nice, isn’t it?</p><p>And it even could be prettier… If we wan’t to compose more and more items, this could be very complex at the end, and start to look like a horizontal pyramid. But we have another great friend…</p><h3>Monad Comprehensions</h3><p>In several functional and hybrid languages there are syntax elements designed to ease composing monads (while making it look like imperative sequential side-effecting code blocks).</p><p>For example, in Scala there is the so-called <em>for-comprehension. </em>Let’s see how our code looks like with that (well, since we would like to add some lettuce to our tortilla as well):</p><pre>for {<br>  fridge &lt;- Kitchen.containers.find(_.name == &quot;fridge&quot;)<br>  lettuce &lt;- fridge.content.find(_ == &quot;lettuce&quot;)<br>  tortilla &lt;- Kitchen.containers.find(_.name == &quot;tortilla&quot;)<br>  _ = tortilla.content += lettuce<br>  _ = fridge.content -= lettuce<br>} yield lettuce</pre><p><em>Some side notes for the code: as we don’t want to deal with the result of adding and removing the lettuce, we can use _ (underscore) just as a variable to simply “pass them to the void”. And here as we are using “unwrapped” plain items (not </em><em>Options), we simply utilise </em><em>= on them, not </em><em>&lt;- (which is actually </em><em>flatMap).</em></p><p>Less work, more beauty (I know it’s subjective), but the same result as with flatMap :</p><pre>val res2: Option[String] = Some(lettuce)</pre><p>Of course Options are not the real big deal in the world of monads, but I thought they could serve as an appetiser and can start you on a journey of the realm of these colorful creatures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCpGIMXrNMHBwIp4uEFONQ.png" /></figure><p>See you later!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12f3ffcbb629" width="1" height="1" alt=""><hr><p><a href="https://medium.com/emarsys-craftlab/monads-12f3ffcbb629">Monads!</a> was originally published in <a href="https://medium.com/emarsys-craftlab">Emarsys Craftlab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Higher order functions]]></title>
            <link>https://medium.com/emarsys-craftlab/higher-order-functions-4bc5929c8b95?source=rss-5df1c09b5f4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bc5929c8b95</guid>
            <category><![CDATA[programming-paradigms]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[emarsys-dev]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <dc:creator><![CDATA[Gábor Manner]]></dc:creator>
            <pubDate>Mon, 27 May 2024 11:37:21 GMT</pubDate>
            <atom:updated>2024-06-19T07:21:44.430Z</atom:updated>
            <content:encoded><![CDATA[<h4>FP is Fun and Practical 4.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxfVbfZ3qH5Khpt_BMF3Vw.png" /></figure><p>To dig deeper in our functional rabbit hole, we have to meet <em>higher order functions</em>. Then we would have more <em>Option</em>s as well ;)</p><h3>What are higher order functions?</h3><p>Put simply, higher order functions are functions that operate on other functions either by taking them as arguments or by returning them.</p><p>This is what makes them “higher order” — they’re operating on a higher level than regular functions.</p><h3>Why are they so cool?</h3><p>By passing functions as arguments or returning them as results, you can create more modular code that can be easily customized and adapted to different situations. This is a key principle of functional programming, which emphasizes the use of small, composable functions that can be combined in different ways to solve complex problems.</p><p>Another advantage of higher-order functions is that they can simplify code by reducing duplication. For example, instead of writing the same code multiple times for slightly different use cases, you can write a higher-order function that takes a function as an argument and performs the common code for you.</p><h3>Break it down!</h3><p>Since I was a little child, I’ve loved to understand things by disassembling them to see their very inside and what moves or makes them, then trying to put them back together again to see how their tiny parts were connected.</p><p>It worked the best for me to learn things. Even the bitter reality that some things are just not eligible for disassembling and some are not able to be put together again. But I tried hard.</p><p>Maybe I have become an expert disassembler and just an intermediate assembler (no, not that <a href="https://en.wikipedia.org/wiki/Assembly_language#Assembler">assembler</a>!).</p><p>So let’s build our higher order function!</p><h3>Each to your own</h3><p>It is very likely that you work a lot with collections (e.g. arrays, lists, sets, etc.). And you often need to do the same thing with each of their elements — you convert them or process them the same way. And it is also likely that you need to do several things with them one right after the another.</p><p>It can be wearing to iterate through your collection again and again and call a function on the elements each time.</p><p>So why not create a function, which applies another function to each item in our collection. And let’s keep it as simple as possible, so we are not going to use types or another fancy stuff, and we write it in the good old Javascript. And because it <em>maps</em> or transforms each element in an array to a new value based on a provided function, let’s call it map:</p><pre>function map(array, func) {<br>  const resultArray = [];<br><br>  for (let i = 0; i &lt; array.length; i++) {<br>    newArray.push(func(array[i]));<br>  }<br><br>  return resultArray;<br>}</pre><p>Voilá! Now, Dear Reader, let me introduce you to your new best friend, a higher order function.</p><p>Well, then we can use it like this:</p><pre>const stringNumbers = [&quot;42&quot;, &quot;53&quot;, &quot;26&quot;, &quot;10&quot;];<br><br>const intNumbers = map(stringNumbers, parseInt);<br><br>// the result: [42, 53, 26, 10];</pre><h3>Back to the Options again</h3><p>Now let me get back to Scala as I feel more comfortable in it than Javascript. And for the goodness to have Options (and types in general) as well :)</p><p>In Scala there are a lot of built-in higher order functions. Many of them can be used to manipulate and transform the value inside an Option in a functional style, making it easier to work with optional values in a safe and concise way.</p><p>Like in my previous post, we used map to apply our function only if it had an existing value.</p><p>As I mentioned earlier, Option can also be viewed as an at-last-one-element collection. But please note, technically it is not really that.</p><p><em>In earlier versions of Scala (before version 2.13), the </em><em>Option type was indeed considered to be a subtype of the </em><em>Iterable type, which is the base type for all collection types in Scala. This meant that </em><em>Option had many of the same methods and behaviors as collections, including the ability to functional programming constructs that are typically used with collections.</em></p><p><em>However, this approach was not always ideal because </em><em>Option and collections have different semantics. So in later versions </em><em>Option was therefore made a standalone type for better separation of concerns between </em><em>Option and collections, and makes it clearer that </em><em>Option is not a collection type.</em></p><p>They have almost the same higher order functions which can be used similarly, but they have different implementations.</p><p>But now we are just here to be impressed by their magic, and not for examining their clockworks under the hood. Maybe sometimes later…</p><h3>Start of Something Beautiful</h3><p>To set up our journey in the world of higher order functions — for just a few examples on Options and collections, let’s create a playlist!</p><p>Our Songrepresentation looks like this:</p><pre>case class Song(artist: String, title: String, featuring: Option[String], lenghtInSec: Int)</pre><p><em>Note: </em><em>case classesin Scala are something similar to POJOs in Java (Plain Old Java Objects), they are just simple object representations with properties, but without the need to implement getters and setters for them. So they are simple as f…fun!</em></p><p>Our songs always have an artist and a title, but not in every case have an additional featuring artist, so it is an optional value. I’ve added a field with the length in seconds just for some further fun.</p><p>So, let’s see our playlist (It is actually a part of one of my real playlists):</p><pre>val playlist: List[Song] = List(<br> Song(&quot;Porcupine Tree&quot;, &quot;Start of Something Beautiful&quot;, None, 439),<br> Song(&quot;Long Distance Calling&quot;, &quot;The Nearing Grave&quot;, Some(&quot;Jonas Renkse&quot;), 467), <br> Song(&quot;Deftones&quot;, &quot;Passenger&quot;, Some(&quot;Maynard James Keenan&quot;), 368),<br> Song(&quot;The Ocean&quot;, &quot;Devonian: Nascent&quot;, Some(&quot;Jonas Renkse&quot;), 665),<br> Song(&quot;Porcupine Tree&quot;, &quot;Arriving Somewhere But Not Here&quot;, None, 774)<br>)</pre><p>Sorry, I know it is not the list of the happiest hits of the year (even not the shortest ones :D), but here are the shiny higher order functions to make us smile:</p><h3>A map to the treasure</h3><p>So you just need the artists from the playlist. Here’s a map to help you to “find them”:</p><pre>val artists = playlist.map(_.artist)<br><br>// it will be: List(Porcupine Tree, Long Distance Calling, Deftones, The Ocean, Porcupine Tree)</pre><p>That’s it!</p><p>Maybe it needs some explanation. The _ (underscore) in this example is just a shorthand notation for anonymous functions (to the current element itself) which is often used when working with higher-order functions. So it is the same as you had written this:</p><pre>val artists = playlist.map(song =&gt; song.artist)</pre><p>As we discussed it earlier (I “discussed” it to you :D) — and even implemented it in Javascript — map applies a given function to each element of a collection.</p><p>And as I told you in the <a href="https://medium.com/emarsys-craftlab/it-is-good-to-have-an-option-ef4ad3f95837">previous episode</a>, it also can be used on an Option and this way it <em>applies the given function to the optional value only if it exists.</em></p><p>So you if you want a list of the first characters of the featuring artists (I don’t really know why you want that, but if you like it, why not), you can get it with map (the inner one) without worrying it fails on the items where there are no values.</p><pre>val firstCharsOfFeaturings = playlist.map(_.featuring.map(_.charAt(0)))</pre><p><em>Here we use a </em><em>map to iterate through each songs in our list, then we use another </em><em>map in it, which applies the </em><em>charAt function to the optional values.</em></p><p>This way you will get a List of Options with the first characters (or their absence as None). So it will be a</p><pre>val firstCharsOfFeaturings: List[Option[Char]] = List(None, Some(J), Some(M), Some(J), None)</pre><h3>flatMap</h3><p>In the previous example you had a magical map which guided you to a mountain which looks like this: List[Option[Char]]</p><p>It is good when you want to deal with the absent values as well, but if you just need a list of first characters of the existing names only then you need to flatten it.</p><pre>val justTheFirstChars: List[String] = firstCharsOfFeaturings.flatten<br><br>// Now you have: List(&quot;J&quot;, &quot;M&quot;, &quot;J&quot;)</pre><p>Or use flatMap which takes you to this flat land in one step</p><pre>val justTheFirstCharsOfFeaturings: List[String] = playlist.flatMap(_.featuring.map(_.charAt(0)))<br><br>// it is also List(&quot;J&quot;, &quot;M&quot;, &quot;J&quot;) this way</pre><p>So never forget: A flat map in your backpack, and the nested is no setback!</p><p>BTW flatMap is much more interesting than just a flattening map, it is a real superhero, but I’ll will talk about it later.</p><p>It will be one of the main protagonists in our next story.</p><p>But until then, let’s see some other common (and practical) higher order functions:</p><h3>filter</h3><p>The filter function is a higher-order function that takes a predicate (a function that returns a boolean) and returns a new collection containing only the elements that satisfy the predicate.</p><p>Collect all songs which have a featuring artist:</p><pre>val hasFeaturing = playlist.filter(_.featuring.nonEmpty)<br><br>// result: List(Song(&quot;Long Distance Calling&quot;,&quot;The Nearing Grave&quot;,Some(&quot;Jonas Renkse&quot;),467), Song(&quot;Deftones&quot;,&quot;Passenger&quot;,Some(&quot;Maynard James Keenan&quot;),368), Song(&quot;The Ocean&quot;,&quot;Devonian: Nascent&quot;,Some(&quot;Jonas Renkse&quot;),665))</pre><h3>reduce</h3><p>reducetakes a binary operator (a function that takes two arguments of the same type and returns a value of that type) and applies it to the elements of a collection, accumulating a result. So it can reduce a collection of a specific type to only one element of that type.</p><p>This way we can find our longest song:</p><pre>val longestSong: Song = playlist.reduce { (current, next) =&gt;<br>  if (current.lenghtInSec &gt; next.lenghtInSec)<br>    current<br>  else<br>    next<br>}<br><br>//result: Song(&quot;Porcupine Tree&quot;, &quot;Arriving Somewhere But Not Here&quot;,None,774)</pre><h3>Folding</h3><p>fold is a special (and more general) reduce function. It takes an initial value and a binary operator which is applied to the elements of the collection and even to the initial value.</p><p>If we want to have the overall length of our playlist, we can get this way:</p><pre>val playtime: Int = playlist.map(_.lenghtInSec).fold(0)(_ + _)<br><br>// the result is 2713</pre><p>It is also a shorthanded version, so let’s see how it looks in a more verbose way:</p><pre>val playtime: Int = playlist.map(_.lenghtInSec).fold(0)( (acc, length) =&gt; acc + length )</pre><p>First we map our Songlist to be a list of lengths. Then we add each element to the previous one-by-one. Starting with the initial value and the first element in the collection.</p><p>So fold iterates through each elements and applies the binary operator to it, while provides the <em>accumulator</em> (acc) and the current element in a tuple as parameters for each step.</p><p>And, of course, if our collection is empty, we get the initial value as a result.</p><p>Following this logic, it is more easily understandable why fold is often used with Option instead of if-else or pattern-matching to handle both its states :</p><pre>val something: Option[String] = Some(&quot;thing&quot;)<br><br>val result: String = something.fold(&quot;It&#39;s nothing&quot;)(_ =&gt; &quot;It&#39;s really something&quot;)<br><br>// In this case the result is a String with a value &quot;It&#39;s really something&quot;</pre><p>There are two more generalised versions of fold: foldLeft and foldRight . They are similar to foldbut you can accumulate your elements to any type of value, regardless your collection type. So we can achieve the same result as before in a single step with foldLeft :</p><pre>val playtime: Int = playlist.foldLeft(0)((acc, song) =&gt; acc + song.lenghtInSec)<br><br>// the result is an Integer value of 2713 here as well</pre><p>So foldLeft and foldRightcombines the elements of a collection using a given function, starting with an initial value. foldLeft starts from the left-most element, while foldRight starts from the right-most element.</p><p>Please note, there is another significant difference in fold tofoldLeft / foldRight , more then it requires the same type as our collection: while foldLeft and foldRight are applied in a determined order, foldapplied in no particular order, so the <strong>function needs to be commutative</strong>.</p><p>That’s all folks, for now! See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bc5929c8b95" width="1" height="1" alt=""><hr><p><a href="https://medium.com/emarsys-craftlab/higher-order-functions-4bc5929c8b95">Higher order functions</a> was originally published in <a href="https://medium.com/emarsys-craftlab">Emarsys Craftlab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[It is good to have an Option]]></title>
            <link>https://medium.com/emarsys-craftlab/it-is-good-to-have-an-option-ef4ad3f95837?source=rss-5df1c09b5f4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef4ad3f95837</guid>
            <category><![CDATA[imperative-programming]]></category>
            <category><![CDATA[optional-type]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[emarsys-dev]]></category>
            <dc:creator><![CDATA[Gábor Manner]]></dc:creator>
            <pubDate>Tue, 14 May 2024 09:02:22 GMT</pubDate>
            <atom:updated>2024-05-14T09:02:22.206Z</atom:updated>
            <content:encoded><![CDATA[<h4>FP is Fun and Practical 3.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*H7WjiKhX37acAqIm9lCM1Q.jpeg" /></figure><p>When I have first met Scala, one of the concepts I got to love very soon was Option. And I haven’t even known that with this thing in my hand I was just standing at the corridor of functional programing.</p><p>However, to be honest, I wasn’t even sure I wanted to be there in the first place.</p><p><em>Option</em> in Scala is a so-called <em>optional type</em> or <em>maybe type</em> and is for representing the presence or absence of a value in a type-safe manner.</p><p>It is not the key to functional programming, only a good taste for it, or an appetizer before entering the realm of FP.</p><h3>Optional vs nullable type</h3><p><em>Optional</em> can be used for similar purposes as <em>nullable types </em>in other languages, but without the risk of that sneaking, dreadful <em>NullPointerException</em>.</p><p>With <em>Option</em> you bake in the optional nature of the value at compile time, so it ensures that you deal with both the presence and the absence of an element. And there’s no need to fear that a <em>NullPointerException</em> rears its ugly head.</p><p>You don’t have to preventively check for null values, you deal with them only when it is effectively needed.</p><p>I think it is already a big deal, but it’s just not the end of the story…</p><p>As I have the most experience with Scala, I’ll use it for my examples, but the concept of <em>optional type</em> exists in other functional (or hybrid) languages as well, eg.:</p><ul><li>Optional in Java (from ver. 8)</li><li>Maybe in Haskell, Elm</li><li>Option in F#, Rust</li></ul><h3>Let’s have an Option!</h3><p>In Scala you can create your <em>optional value</em> through a <em>type constructor</em> like this:</p><pre>val something: Option[String] = Some(&quot;yes it is a string&quot;)</pre><p>or for a not-existing value:</p><pre>val nothing: Option[String] = None</pre><p>So <em>optional values</em> in Scala are represented by Some[T](present) or None[T](absent) — both are inherited from Option[T].</p><p>With <em>Option</em>s you can do a lot of things, eg. you can use it in the old defensive imperative way (for the sake of simplicity we just print out our value to the console):</p><pre>if (something.nonEmpty) {<br>  println(something.get)<br>} else {<br>  println(&quot;it has no value&quot;)<br>}</pre><p>Note: we call the getfunction on our <em>value</em> to take our inner value out of the <em>Option</em> container.</p><p>Beware, if we call geton a Nonevalue we get a <em>NoSuchElementException. </em>Yes, it’s not really better than<em> NullPointerException. </em>But don’t worry, we don’t even have to use it this way (and now it is even deprecated from Scala 3). There are several other methods which are more practical, and some are even more functional.</p><p>For example it can be less messy with <em>pattern matching:</em></p><pre>something match {<br>  case Some(value) =&gt; println(value)<br>  case None =&gt; println(&quot;it has no value&quot;)<br>}</pre><p>Or you can use some kind of “default valueing” by getOrElse<em>. </em>It produces the same result as both codes above:</p><pre>println(something.getOrElse(&quot;it has no value&quot;))</pre><p>We can go further and be even more “functional and practical”, and just print the value if it is present (and do nothing if it is absent).</p><pre>something.map(println)</pre><p>map<strong><em> </em></strong>function<strong><em> </em></strong><em>takes a function as a parameter and applies it to the optional value (only) if it exists.</em></p><h3>Option as a collection</h3><p>Option can also be viewed as a one element collection. Like a Listwhich can have at last one value, but can be empty as well.</p><p>So this way we can say <em>map</em> applies the function (taken from the parameter) to each element of a <em>collection</em>.</p><p>We can <em>traverse</em> our <em>Option</em>s the same way as real <em>collection</em>s. This way we can write more fluid code-flow (with fewer errors) without explicitly checking the existence of the value.</p><pre>val result = something<br>  .map(_.toUpperCase)<br>  .filter(_.startsWith(&quot;YES&quot;))<br>  .map(_.take(9))<br>  .getOrElse(&quot;NO!&quot;)</pre><p>It is just a very silly example to demonstrate this. We get the first 9 characters of our string, converted to uppercase, only in the case if it starts with “YES” — or “yes” as it is checked when it is already converted. Otherwise we get “NO!”. And more importantly it won’t fail if we have no value.</p><p>Now compare it to the “usual” way with a <em>nullable value</em>, in an imperative setting (pseudo code):</p><pre>var result = &quot;NO!&quot;;<br><br>if (something != null) {<br>  var converted = something.toUpperCase()<br>  <br>  if (converted.startsWith(&quot;YES&quot;)) {<br>    result = converted.take(9)<br>  }<br>}</pre><p>As you can see, you have to <em>defensively</em> handle the non-existence of the value. Plus you had to introduce a temporary variable (“<em>converted”</em>) as well to store the uppercase string.</p><p>However, probably it’s a matter of taste, but I really don’t like that you have to declare your result variable with “NO!” as an initial value before the real implementation of the logic if you don’t want to handle both “negative” output separately and set <em>result = “NO!”</em> twice adding <em>else</em> blocks to the <em>if</em> conditions (1. in case of null value, 2. when not starts with “YES”) inside.</p><h3>What’s more?</h3><p>With functional idioms like <em>monadic operators</em> and <em>higher-order functions</em> Optioncan show even more of its real power.</p><p>But what are these weird sounding things anyway? We will see it in the next episode.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef4ad3f95837" width="1" height="1" alt=""><hr><p><a href="https://medium.com/emarsys-craftlab/it-is-good-to-have-an-option-ef4ad3f95837">It is good to have an Option</a> was originally published in <a href="https://medium.com/emarsys-craftlab">Emarsys Craftlab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Be functional!]]></title>
            <link>https://medium.com/emarsys-craftlab/be-functional-3741383eb15d?source=rss-5df1c09b5f4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3741383eb15d</guid>
            <category><![CDATA[programming-paradigms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[declarative-programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[emarsys-dev]]></category>
            <dc:creator><![CDATA[Gábor Manner]]></dc:creator>
            <pubDate>Wed, 01 Mar 2023 08:12:46 GMT</pubDate>
            <atom:updated>2023-03-01T08:12:46.673Z</atom:updated>
            <content:encoded><![CDATA[<h4>Talking to an adult — FP is Fun and Practical 2.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QjulhfvvIBj8G1COOFTrpw.jpeg" /></figure><p>For part 1 of the series, <a href="https://blog.craftlab.hu/c7df90ba702">click here</a>.</p><h3>Imperative vs. declarative</h3><p>There’s a saying <a href="https://www.youtube.com/watch?v=E8G2ByTQzuY">Venkat Subramaniam</a> uses a lot for comparing imperative vs. declarative programming style and I like it very much as it is so expressive:</p><blockquote><em>Imperative style is where you tell WHAT to do AND HOW TO actually do that.<br>While declarative style is where you tell WHAT to do AND NOT HOW TO do that.</em></blockquote><p>Sometimes he goes further and says: “Imperative style is like talking to children. You have to say everything — and repeat it on the next day”</p><p>So let’s see them by some real life examples!</p><h3>How to ask for some milk?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*kMxNSUd0HhykbMgL.jpg" /></figure><h4>Imperative</h4><p>You specify every single step:</p><pre>1. Open the fridge<br>2. Take the box out of the fridge<br>3. If it is not milk (can be orange juice as well) put it back and take another one.<br>4. Repeat it, until you get the milk or there are no more boxes<br>5. Pour it in a glass<br>...</pre><pre>n. Give it to me</pre><h4>Declarative</h4><p>You declare pieces of information/functions and pronounce your goal. All you have to do is to combine (compose) them:</p><pre>- The milk is in the fridge.<br>- Milk is a thing which is in a box with the text &quot;Milk&quot; on it.     Hopefully :)<br>- I want (a Glass of*) milk</pre><pre>Here you are.</pre><p>* if we are in a <a href="https://medium.com/@thiago_silva/what-is-type-safety-ceb8f14ee6c3"><em>type-safe</em></a> environment we can actually say we want a <strong>glass of</strong> milk, since it is also known that <em>Glass</em> is a format (*cough… <em>type</em>) which makes milk transferable and containable for our hands and easily consumable for us.</p><h3>Okay, but I’m not a baby, I’m not here for milk! Got code?</h3><p>Okay, let me show you the above situation by p̶s̶e̶u̶d̶o̶-̶c̶o̶d̶e… j̶a̶v̶a̶s̶c̶r̶i̶p̶t… some pseudo-code that resembles Javascript.<br>I like the <a href="https://dev.to/kwereutosu/the-k-i-s-s-principle-in-programming-1jfg">KISS</a> principle, so I made it really simple and really-really stupid, just to focus on the way how you implement these different approaches. I lowered my desires in quality and dropped the fridge. Now there are just some boxes of drinks, and I don’t need glasses, but I want all that (likely) contains milk!</p><pre>const boxes= [<br>    {text: &quot;orange&quot;, content: &quot;orange&quot;},<br>    {text: &quot;tomato&quot;, content: &quot;tomato&quot;},<br>    {text: &quot;milk&quot;, content: &quot;eggnog&quot;},<br>    {text: &quot;milk&quot;, content: &quot;milk&quot;},<br>    {text: &quot;best before: 2020&quot;, content: &quot;yikes&quot;},<br>    {text: &quot;milk&quot;, content: &quot;nothing&quot;}<br>]<br><br>// Be imperative!<br><br>function findMilkImperative(boxes) {<br>    const boxesToGive = [];<br>    for (const box of boxes) {<br>        if (box.text == &quot;milk&quot;) {<br>            boxesToGive.push(box);<br>        }<br>    }<br>    return boxesToGive;<br>} /* So you say: <br>     iterate through each of the boxes <br>     and if it says &quot;milk&quot; then collect it <br>     and then deliver them to me */<br><br><br><br>// Be functional!<br><br>function findMilkDeclarative(boxes) {<br>    return boxes.filter(box =&gt; box.text == &quot;milk&quot;)<br>} // Got it? Gimme! ... Got it?</pre><p>Both these functions will return you a <em>collection</em> of all the boxes with the text “milk” on them. So WHAT they do is the same.</p><pre>[<br>    {text: &quot;milk&quot;, content: &quot;eggnog&quot;},<br>    {text: &quot;milk&quot;, content: &quot;milk&quot;},<br>    {text: &quot;milk&quot;, content: &quot;nothing&quot;}<br>]</pre><p>But HOW you implement them is way too different.</p><h3>Get to the fridge!</h3><p>I know now you say: “It’s nice, but it’s just <a href="https://en.wikipedia.org/wiki/Syntactic_sugar"><em>syntactic sugar</em></a>”.</p><p>And you are kinda right. Actually the declarative approach can show its real power in more complex situations.</p><p>Like when these boxes are in the fridge in the kitchen.</p><p>If we are ‘imperators’ we have to tell that “child” more and more step by step instructions: how to get to the kitchen and that they have to open the fridge door to get that milk. Not forgetting about to close it after all.</p><h3>And what if the fridge door remains open?</h3><p>A <em>side effect</em> happens…</p><p><em>A side effect means that something else is being changed other than what was intended. In programming it is a change in the state of something outside its scope (eg. a value of a variable, writing to a disk or to the console, etc.)</em></p><p>As in real life in your fridge — where terrible things can arise in your delicacies — , it can make your code indeterministic, or strange bugs can pop up.</p><p>While we just wanted some milk.</p><p>However, when we live in a declarative world it can happen the adult you ask is a superhero and can take the milk out of the fridge without opening it, what’s more, it is possible they can fetch it for you by walking straight through the walls!</p><p>You just have to know what you want, and not how it can be achieved.</p><p>And you don’t even have to take care about that damn fridge door, so you need have no fear of <em>side effects</em>.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3741383eb15d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/emarsys-craftlab/be-functional-3741383eb15d">Be functional!</a> was originally published in <a href="https://medium.com/emarsys-craftlab">Emarsys Craftlab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FP is Fun and Practical]]></title>
            <link>https://medium.com/emarsys-craftlab/fp-is-fun-and-practical-c7df90ba702?source=rss-5df1c09b5f4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7df90ba702</guid>
            <category><![CDATA[emarsys]]></category>
            <category><![CDATA[declarative-programming]]></category>
            <category><![CDATA[emarsys-dev]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Gábor Manner]]></dc:creator>
            <pubDate>Wed, 22 Feb 2023 13:48:13 GMT</pubDate>
            <atom:updated>2023-02-22T14:05:12.944Z</atom:updated>
            <content:encoded><![CDATA[<p>I have come to a point in my life where I felt I had to share my thoughts and experience with Functional Programming (FP).</p><p>When people meet functional programming for the first time, they usually find it weird or think it’s an exotic style of coding, which is way too complicated. And imagine its enthusiasts and prophets as some weirdos, math-maniacs or just a bunch of snobbish, elitist freaks.</p><p>Well… I can understand and there was a time when I felt something similar, but now I couldn’t agree less. FP is just not the same what we are used to. Most of us learned to code imperatively (in the form of OOP), that is how we think and build up our codes. But Functional Programming is just another state of mind, a different approach on how to control and structure programs. It is not more difficult but just as difficult as imperative or procedural — in another way :) And you don’t have to be an academic to see its benefits.</p><p>There are a lot of sources where you can learn FP and even some that tell you this is the future or the only true way, or the most reasonable choice for developing. And often it seems that developers are split into two camps. The “FPists” and the “OOPists”. But I don’t want to strengthen any of those camps, and also</p><h3>I don’t want to</h3><ul><li>teach you how to program functionally.</li><li>convince you that FP is basically better than anything else.</li></ul><h3>But I’d like to</h3><ul><li>introduce it to you, if you have never met,</li><li>or make you friends if you have met, but it looked terrifying or difficult,</li><li>share my love of FP and the reasons why,</li><li>and try to show some practical examples as well.</li></ul><p>Sorry, but I can’t do it completely objectively. So it will be a strange love story about how I learned to stop worrying and love the FP.</p><h3>TLDR</h3><p>I’ll start with some intro and explanation about functional (and declarative) programming, and some pre-summary of the things I am about to tell you in the later episodes. Stay tuned and come back next week for newer posts.</p><h3>What is functional programming?</h3><p>In brief — and maybe by a not-so-professionally written definition — functional programming is a programming paradigm where you build your programs by applying and composing functions without explicitly describing the flow control — avoiding shared state, mutating data and side-effects. It is a particular kind of declarative programming.</p><h3>Functional versus OOP</h3><p>Functional programming is often defined in opposition to object-oriented programming — or its broader set: imperative programming — , and it is suggested that you have to choose between them. That is misleading as these approaches are not mutually exclusive, and while you make your application based on OOP you still can use the functional approach in certain parts to solve different problems in it.</p><p>I have to admit it, the other way around is rare. Hardcore functional dudes like to stay pure. ;)</p><h3>Which one is the best?</h3><p>Many of us was taught that OOP</p><ul><li>is the weapon of choice to fight against the so-called “spaghetti”, the poorly written, badly structured code.</li><li>And it is the best and most logical way to build up your applications as it models the real world.</li></ul><p>Then you find some articles or meet some FP-folks who state that functional (or declarative programming)</p><ul><li>helps you to write code in a logic which is more close to human thinking (even more if they are mathematicians),</li><li>and your code is more reliable,</li><li>easier to maintain and refactor or even test it,</li><li>changes are often easier to implement,</li><li>and they are more resistant to bugs,</li><li>and it improves the quality and predictability of your code.</li></ul><h3>But where’s the truth?</h3><p>So which one is the winner? Let’s stay rational. Neither of them is the silver bullet. They all have their advantages, drawbacks and limits. I think that the winner is the open-minded, passionate developer who dives into each paradigm and has the (infinite) time and energy to master their knowledge in either way, and has the possibility and judgement to choose and apply the right tool to solve their particular problem.</p><p>But I’m just here now to promote functional programming, so let’s see..</p><h3>Declarative and Functional</h3><p>In these articles I often use <em>functional</em> and <em>declarative </em>terms as well. But please note, as Functional Programming is a subset of Declarative Programming, everything which is applicable to Functional is also valid to Declarative, but it is not necessarily true vice-versa.</p><h3>Why I like FP</h3><h3>Talk less do more</h3><p>I’m an introvert. I don’t like to talk too much (okay, there are some exceptions eg. movies, music, books, some science topics and bad puns), and I really-really hate to say or listen to unnecessary (needless?) things or say out loud the self-evident (or the ones I think are self-evident). They make me nervous inside. And I like to code and solve problems. And if I have an idea I like to see it working (or failing) in less time and by the least words as possible. and FP helps you to talk less and do more:</p><ul><li>with writing less boilerplate,</li><li>telling what to do and not telling how to do it step by step,</li><li>without the necessity of introducing temp variables,</li><li>without the need of breaking out from code blocks and making logical jumps from one part of code to another,</li><li>and without multi-level horizontal pyramids built by conditional statements.</li></ul><h3>Other key points</h3><ul><li>Less unexpected behaviours and hard to follow processes by neglecting inner state changes (easier to debug).</li><li>Immutability, thread safety, easier to implement and handle parallelism and concurrency.</li><li>Avoiding side effects, or keep and handle them in their place, and — maybe even more important — in their time!</li><li>Lazy evaluation.</li><li>Composing and combining functions. Functions as values.</li><li>It gives you another way of thinking and point of view (even if you’d rather stay in imperative programming).</li><li>And I really like <em>For Comprehension</em> :)</li><li>And of course, <em>Option</em>s!</li></ul><p>So come with me, let’s see how to talk to this tiny freaky creature!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7df90ba702" width="1" height="1" alt=""><hr><p><a href="https://medium.com/emarsys-craftlab/fp-is-fun-and-practical-c7df90ba702">FP is Fun and Practical</a> was originally published in <a href="https://medium.com/emarsys-craftlab">Emarsys Craftlab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>