<?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 Hung Nguyen on Medium]]></title>
        <description><![CDATA[Stories by Hung Nguyen on Medium]]></description>
        <link>https://medium.com/@hungnq1989?source=rss-2db1a804f5e2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*dmjvmJPgmBfpc799.jpeg</url>
            <title>Stories by Hung Nguyen on Medium</title>
            <link>https://medium.com/@hungnq1989?source=rss-2db1a804f5e2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:47:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hungnq1989/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[fp-ts for the impatient]]></title>
            <link>https://medium.com/@hungnq1989/fp-ts-for-the-impatient-ad6c0a9a257b?source=rss-2db1a804f5e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad6c0a9a257b</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[fpt]]></category>
            <dc:creator><![CDATA[Hung Nguyen]]></dc:creator>
            <pubDate>Sun, 20 Feb 2022 22:03:42 GMT</pubDate>
            <atom:updated>2022-02-21T17:46:15.499Z</atom:updated>
            <content:encoded><![CDATA[<p>Read this on my personal site <a href="https://butchiso.com/2022/02/fp-ts-for-the-impatient.html">https://butchiso.com/2022/02/fp-ts-for-the-impatient.html</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*vFivMvi95VXSUO01UOKxWg.png" /></figure><h3>Introduction</h3><p>This post is an express tour for busy people who want to quickly adopt <a href="https://gcanti.github.io/fp-ts/">fp-ts</a>. In this brief introduction, we don’t go through the what is functional programming as well as its advantages/disadvantages.</p><p>You don’t really need to understand all mathematics concepts in order to learn functional programming. IMO, you only need to to know how each operator works. Once you get to know each basic operators in fp-ts, you can go back and review the mathematic theory.</p><h3>Pipe, flow</h3><h3>Pipe</h3><p>In <strong>fp-ts</strong> pipe is a function, but in pure functional programming language (like Haskell) it’s an operator. JavaScript also has a proposal for it (see <a href="https://github.com/tc39/proposal-pipeline-operator">Pipe Operator (|&gt;) for JavaScript</a>)</p><p>It’s the basic building block of fp-ts, you can use <a href="https://gcanti.github.io/fp-ts/modules/function.ts.html#pipe">pipe</a>() to chain the sequence of functions from left to right</p><p>Let’s look at this simple example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1e141866d51ba53a853b4451ba1e569/href">https://medium.com/media/f1e141866d51ba53a853b4451ba1e569/href</a></iframe><p>The result of this operation is <em>5</em>. It’s self-explanatory but we can look at these steps:</p><ol><li>We start with the value of <strong>1</strong>.</li><li><strong>1</strong> is piped into the first argument of <em>add1 </em>and <em>add1 </em>is evaluated to <em>2</em> by adding <em>1</em>.</li><li>The return value of <em>add1</em>, <em>2</em> is piped into the first argument <em>add3 </em>and is evaluated to <em>5</em> by adding <em>3</em>.</li></ol><p>At this point, the pipe receives a number as input and output a new number, but we can also do something else like input a string from a number also.</p><pre>const meowify = (num: number): string =&gt; {<br>  return &quot;meow &quot;.repeat(num).trim();<br>};</pre><pre>pipe(1, add1, add3, meowify); // &#39;meow meow meow meow meow&#39;</pre><p>Note that we cannot put the <em>meowify </em>function in between <em>add1 </em>and <em>add3 </em>functions like this</p><pre>❌ pipe(1, add1, meowify, add3)</pre><h3>Flow</h3><p>The flow operator is very similar to pipe operator, the difference is the first argument of flow must be a function. For example, we can use the three functions above to form a flow like this:</p><pre>import { flow, pipe } from &quot;fp-ts/lib/function&quot;;</pre><pre>flow(add1, add3, meowify)(1); // this is equivalent to pipe(1, add1, add3, meowify)</pre><pre>// Or we can use it like this</pre><pre>pipe(1, flow(add1, add3, meowify)); // &#39;meow meow meow meow meow&#39;</pre><p>In the example with pipe what if we don’t want to feed 1 as the input to the pipe? We probably have to do this:</p><pre>const meowify1 = (n: number) =&gt; pipe(n, flow(add1, add3, meowify)</pre><pre>// but with flow you don&#39;t need to</pre><pre>const meowify2 = flow(add1, add3, meowify)</pre><p>Tip: If you have a long curried functions, you can use ap from Identity monad to apply all arguments</p><pre>import { ap } from &quot;fp-ts/lib/Identity&quot;;</pre><pre>const makeUrl = (protocol: string) =&gt; (domain: string) =&gt; (port: number) =&gt; {<br>  return `${protocol}://${domain}:${port}`;<br>};</pre><pre>// ✅ right<br>pipe(makeUrl, ap(&quot;https&quot;), ap(&quot;swappie.com&quot;), ap(80)); // https://swappie.com:80</pre><pre>// Equivalent to</pre><pre>makeUrl(&quot;https&quot;)(&quot;swappie.com&quot;)(80);</pre><pre>// ❌ this doesn&#39;t work</pre><pre>pipe(&quot;https://&quot;, &quot;swappie.com&quot;, 80, makeUrl);</pre><h3>Option, Either</h3><h3>Option</h3><p>Options are containers, or specifically an Option is a monad (it’s equivalent to <a href="https://en.wikibooks.org/wiki/Haskell/Understanding_monads/Maybe">Maybe monad in Haskell</a>), that wrap values that could be <em>truthy </em>or <em>falsy</em>. If the values are <em>truthy </em>, we say the <em>Option </em>is of <em>Some </em>type, and if the values are <em>falsy </em>(<em>undefined | null</em>) we say it has the <em>None </em>type.</p><pre>type Option&lt;A&gt; = None | Some&lt;A&gt;;</pre><p>“Why should we use Option types in the first place?” You might ask. We already know that Typescript already has good ways to deal with <em>undefined </em>or <em>null </em>values. For example, we can use <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining"><strong>optional chaining</strong></a> or <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing"><strong>nullish coalescing</strong></a>.</p><p>The answer is: mostly you won’t need to use Option, <strong>optional chaining</strong> can do it as well for you. However the Option type is more than just checking for <strong>null</strong>. Options can be used to represent failing operations, and most importantly you can chain them or in other words you can compose functions that return an <em>Option </em>into a more complex one.</p><p>In most cases you probably don’t need Option, but let see these example to see some benefits of Option monad</p><pre>const findUrl = (array: string[]): string | undefined =&gt;<br>  array.find((item) =&gt; item.startsWith(&quot;http&quot;));</pre><pre>const makeA = (url: string | undefined): string =&gt;<br>  url ? `&lt;a href=${url}&gt;${url}&lt;/a&gt;` : &quot;no link&quot;;</pre><pre>const parseLink = (array: string[]): string =&gt; makeA(findUrl(array));</pre><pre>// execute<br>const input = [&quot;[&quot;, &quot;google&quot;, &quot;]&quot;, &quot;(&quot;, &quot;http://www.google.com&quot;, &quot;)&quot;];</pre><pre>console.log(parseLink(input)); // &lt;a href=http://www.google.com&gt;http://www.google.com&lt;/a&gt;</pre><pre>console.log(parseLink([])); // no link</pre><p>The code above can be converted to fp-ts</p><pre>import * as O from &quot;fp-ts/lib/Option&quot;;</pre><pre>// O.fromNullable convert a non-nullable value to Some(value) and nullable<br>// to None</pre><pre>const findUrl = (array: string[]): O.Option&lt;string&gt; =&gt;<br>  O.fromNullable(array.find((item) =&gt; item.startsWith(&quot;http&quot;)));</pre><pre>const makeA = (url: string): string =&gt; `&lt;a href=${url}&gt;${url}&lt;/a&gt;`;</pre><pre>const parseLink = flow(<br>  findUrl,<br>  O.fold(() =&gt; &quot;no link&quot;, makeA)<br>);</pre><pre>const input = [&quot;[&quot;, &quot;google&quot;, &quot;]&quot;, &quot;(&quot;, &quot;http://www.google.com&quot;, &quot;)&quot;];</pre><pre>parseLink(input); // &lt;a href=http://www.google.com&gt;http://www.google.com&lt;/a&gt;</pre><pre>parseLink([]); // no link</pre><p>💡 Note that you can <strong>lift</strong> a nullable value to an Option using O.fromNullable</p><h3>Either</h3><p>An Either is a type that represents a <em>synchronous</em> operation that can succeed or fail. Much like Option, where it is <em>Some </em>or <em>None</em>, the Either type is either <em>Right </em>or <em>Left</em>. <em>Right </em>represents success and <em>Left </em>represents failure. It is analogous to the <a href="https://doc.rust-lang.org/std/result/">Result</a> type in Rust.</p><p>This is one practical example of using fp-ts, specially <em>Either </em>for validating a password strength. For each individual functions below, I think they pretty self-explanatory excepts the last one <em>validatePassword</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8edf0dd4db229dd16d71f4217669d456/href">https://medium.com/media/8edf0dd4db229dd16d71f4217669d456/href</a></iframe><p>We can looks at the break-down steps of validatePassword as follow:</p><p>Let’s take this happy path example validatePassword(&#39;salaSANA123&#39;)</p><ol><li>We will start with input salaSANA123 is passed to minLength <br>1.1 It will be evaluated to a Either value that contains a right value salaSANA123</li><li>The return value of minLength(&#39;salaSANA123&#39;) value will be piped to E.chain(oneCapital)<br>2.1 E.chain will unwrap the E.right(&#39;salaSANA123&#39;) to &#39;salaSANA123&#39; value and passes it to oneCapital.<br>2.2 oneCapital(&#39;salaSANA123&#39;) will evaluate the string and returns E.right(&#39;salaSANA123&#39;).</li><li>Again, the return value of oneCapital(&#39;salaSANA123&#39;) will be piped to E.chain(oneNumber) <br>3.1 E.chain will unwrap the E.right(&#39;salaSANA123&#39;) to &#39;salaSANA123&#39; value and passes it to oneNumber<br>3.2 oneNumber(&#39;salaSANA123&#39;) will evaluate the string and returns E.right(&#39;salaSANA123&#39;)</li></ol><p>In any situation that one of the three function returns E.left(new Error(&#39;...&#39;)) the left value is returned immediately</p><p>💡 And just like how you can lift nullable into an Option, you can also lift an Option into another fp-ts container, like Either.</p><pre>const minLength = (s: string): O.Option&lt;string&gt; =&gt;<br>  s.length &gt;= 6 ? O.some(s) : O.none;</pre><pre>...</pre><pre>const validatePassword = (s: string): Either&lt;Error, string&gt; =&gt;<br>  pipe(<br>    minLength(s),<br>    E.fromOption(() =&gt; new Error(&quot;at least 6 characters&quot;)), //<br>    chain(oneCapital),<br>    chain(oneNumber)<br>  );</pre><h3>Task, TaskEither</h3><h3>Task</h3><p>In fp-ts, a Task is basically a js Promise, this is the definition of Task.</p><pre>interface Task&lt;A&gt; {<br>  (): Promise&lt;A&gt;;<br>}</pre><p>From the docs</p><blockquote><em>Task&lt;A&gt; represents an asynchronous computation that yields a value of type </em><em>A and </em><strong><em>never fails</em></strong><em>. If you want to represent an asynchronous computation that may fail, please see </em><em>TaskEither.</em></blockquote><h3>TaskEither</h3><p>Basically <em>TaskEither </em>= <em>Task </em>+ <em>Either</em>, so with <em>TaskEither </em>you can have a <em>Task </em>that may fail.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af24ddaf834142fb0a0d67ea098f4f88/href">https://medium.com/media/af24ddaf834142fb0a0d67ea098f4f88/href</a></iframe><p>The TE.fold function is actually very simple, it accepts two functions (onLeft, onRight) and it will call onLeft on left value and onRight on right value, depends on the previous value from the pipe.</p><h3>Do Notation</h3><p>From the docs</p><blockquote><em>Both </em><a href="https://wiki.haskell.org/Monad#do-notation"><em>Haskell</em></a><em> and </em><a href="https://github.com/purescript/documentation/blob/master/language/Syntax.md#do-notation"><em>PureScript</em></a><em> languages provide syntactic sugar for working with monads in the form of do notation.</em></blockquote><blockquote><em>fp-ts provides it’s own implementation of do notation which can help to simplify effectful code.</em></blockquote><p>You can read about the “official” explanation and example from fp-ts (<a href="https://gcanti.github.io/fp-ts/guides/do-notation.html">see this</a>) about do notation in fp-ts</p><p>Generally speaking, “do notation” allows you bind previous returned values from other functions in the pipe to a context object. Without do notation it’s very hard to maintain the variable scope, since you either to pass it along as intermediate result or go deep into nested pipe.</p><p>This example below does technically nothing much, but it illustrates how you can employ <em>do notation</em> to combine different functions<em> </em>into one <em>pipe </em>and still easily maintain the readability and variable scope.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/410e8bad79aa7b10f82fb9d659222b8f/href">https://medium.com/media/410e8bad79aa7b10f82fb9d659222b8f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad6c0a9a257b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>