<?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 Yassine Elouafi on Medium]]></title>
        <description><![CDATA[Stories by Yassine Elouafi on Medium]]></description>
        <link>https://medium.com/@yelouafi?source=rss-b6f1fc99587d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Yassine Elouafi on Medium</title>
            <link>https://medium.com/@yelouafi?source=rss-b6f1fc99587d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 17:56:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yelouafi/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[An (almost) functional approach to dynamic state]]></title>
            <link>https://medium.com/@yelouafi/an-almost-functional-approach-to-dynamic-state-b8fc1b15b75c?source=rss-b6f1fc99587d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8fc1b15b75c</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[observables]]></category>
            <dc:creator><![CDATA[Yassine Elouafi]]></dc:creator>
            <pubDate>Sun, 30 Oct 2016 00:58:27 GMT</pubDate>
            <atom:updated>2019-02-24T15:31:56.993Z</atom:updated>
            <content:encoded><![CDATA[<h4>Applicative Data-Driven Computations</h4><h3>Motivation</h3><p>A fundamental requirement in GUI applications is to maintain consistency between program state (variables holding some data) and the visual UI. Multiple solutions have been adopted to the above problem, but the most used one remains the <em>Callback and Mutation </em>model</p><ul><li>We attach some event listeners to the UI</li><li>On each event occurrence, we update the program state</li><li>Then have some mechanism to propagate this state change, either manually or automatically by some library.</li><li>And finally project all the changes into the UI, again either manually (imperatively) or automatically using some library/framework.</li></ul><p><em>Another solution is the use of Functional Reactive Programming (FRP): we represent UI events as </em>Streams<em> and then combine those streams using various functions to produce other Streams. Program state can be represented using </em>Behaviors<em>: an abstraction to represent time varying values.</em></p><p>To manage state changes and propagation, one popular way is to use <em>Observables</em>: think of a kind of a Box where we put some value. Each time we modify the value inside the box, the program takes care of notifying the user code. Observables can also be combined to produce other observables, like we combine cells in a spreadsheet to produce other cells. An Observable library also usually provides some declarative way keep the UI up to date with the data in observables.</p><p>In this post, I’d like to share an implementation of Observable-like abstractions using an (almost) pure functional approach. While you will not probably find new shiny concepts here, if you’ve ever tried, as I did, to implement some form of Observables using the traditional Event Emitters and dependency graphes, then you may find the functional approach presented here more compelling and elegant.</p><h3>Credit: Conal Elliot’s paper</h3><p>The approach I propose here is described (purely and more formally) in a Conal Elliot’s (draft) paper <a href="http://conal.net/papers/data-driven/paper.pdf">Applicative Data-Driven Computation</a>.</p><p>The article can be a little hard to follow for those non familiar with the Haskell programming language. In this post I’ll try to present the concept using JavaScript in a hopefully accessible way.</p><p><em>A link to the Gist containing the source code is present at the end of this article</em></p><h3>First, what do we mean by ‘Data-Driven’ ?</h3><p>We’ll start by quoting the first paragraph of the paper</p><blockquote>Graphical user interfaces (GUIs) are usually programmed in an “unnatural” style, in that <strong>implementation dependencies are inverted</strong>, relative to <strong>logical dependencies</strong>. We suggest that this reversal results directly from the imperative, data-driven orientation of most GUI libraries.</blockquote><p>Let’s try to understand what the author means by terms like <em>inverted dependencies</em> and <em>logical dependencies.</em></p><p>Consider this simple example</p><pre>const a = 100<br>const b = divide(a, 10)<br>const c = multiply(a, sum(a, b))</pre><p>In JavaScript, the above lines correspond to <em>executable statements</em> to be executed sequentially (try to put the declaration of c before b, JavaScript will be unable to resolve b, because it’s not yet declared at the time of evaluating c). In a pure FP language like Haskell, there is no notion of executable statements. We&#39;re not telling the compiler to execute the lines above sequentially (in fact We&#39;re not telling it to execute anything). We&#39;re just writing <em>definitions</em> for equivalences. b = divide(a, 10) means literally that the 2 terms of the equation are equivalent, and that the compiler can use divide(a, 10) in place of b, whenever b appears in an expression. We’re not talking about assignment or memory storage, just equations.</p><p>In the example above, to obtain the value of c we <em>demand</em> it (typically via a main function). The compiler starts evaluating c by replacing it with its equivalent term multiply(a, sum(a, b)). Then to evaluate the new term, we substitute multiply with its equivalent definition and so on. This process continues until we can reach irreducible terms (primitive terms which can not be replaced by other terms, like constant literals).</p><p>This form of evaluation, also known as <em>demand-driven evaluation</em>, has one particular property: dependencies are logically resolved in the right order. For example, the program can not evaluate c before b because the value of b is needed in order to evaluate c.</p><p>If this seems all obvious, then you understand what the author means by <em>logical dependencies</em>. When we want to get the value of an expression which depends on other expressions, the expression will evaluate the other sub-expressions it depends on. The dependency chain is automatically resolved through simple function application (or term reduction).</p><p>And now, what could be the meaning of <em>inverted dependencies</em> and D<em>ata-Driven orientation</em>?</p><p>Imagine that we’re programming an UI application, and that the value of a is retrieved from some UI control like an input box. Typically we attach a listener that observes the changes made by the user to the input value, then we update the program state in an imperative way.</p><p>You may be thinking that if we transfer the whole block of the precedent code inside the listener</p><pre>// represents the program state<br>var a, b, c<br>input.addEventListener(&#39;change&#39;, () =&gt; {<br>  a = input.value<br>  b = divide(a, 10)<br>  c = multiply(a, sum(a, b))<br>})</pre><p>Then we get the same result as above. In reality, there is a subtle and an important difference. It’s not obvious to illustrate in an imperative language like JavaScript. To make it more obvious let’s rewrite the first example in a way to mimic an FP language.</p><pre>function a() {<br>  return 100<br>}</pre><pre>function c() {<br>  return multiply(a(), sum((a(), b())<br>}</pre><pre>function b() {<br>  return divide(a(), 10)<br>}</pre><p>Have you noted how we’ve put the c declaration before b. What happens if we invoke c() on the console? do we still get the right value? of course yes. It doesn&#39;t matter at all in which order we put the above declarations. Evaluating a function will always resolve the dependencies in the correct order.</p><p>Now what happens if we change the order in the second example?</p><pre>//...<br>input.addEventListener(&#39;change&#39;, () =&gt; {<br>  a = input.value<br>  c = multiply(a, sum(a, b))<br>  b = divide(a, 10)<br>})</pre><p>Since c is updated before b, its value is computed using a stale value of b. Here you&#39;ll notice that the order in which we put things does crucially matter. We have to put our statements in the correct order of dependencies. Put another way, instead of relying on simple function invocation, which naturally resolves its dependencies in the logical order. We now have the burden to ensure the order of things by ourselves. Or also: instead of starting from the bottom - the output value which is c - and pulling all its inputs, we take the inverse route: we start from the top - the input value which is a - and push updates to all the outputs ourselves. The computation proceeds in an inverted order.</p><p><em>You may object that we can make </em><em>b and </em><em>c simple functions instead of variables, and then update the UI by invoking them. Indeed this is a step in the right direction: do not update derived data, but compute it on demand.</em></p><p><em>However in real code, the situation is much more complex and it&#39;s often tedious to manage derived data manually. Also, we likely need to update some part of the UI which depend on the dynamic data. Managing those dependencies manually is often complex and error prone.</em></p><p>And finally, what’s this Data-Driven thing? It describes a programming style (often associated with Data-Flow architectures) where “the availability of data (inputs) triggers the operations to be executed on it”. In this style of programming, we’re in charge of manually propagating data changes, and thus implementing dependencies correctly in our code. By subscribing to some data sources, each time the data source notifies some change we need to update the dependent data in the correct order.</p><p>Quoting the author again</p><blockquote>While outputs depend on inputs from a user and semantic point of view, the data-driven approach imposes an implementation dependence of inputs on outputs.</blockquote><p>also</p><blockquote>This paper presents simple, functional interfaces for data-driven programming in general and GUI programming in particular, in which program dependencies directly mirror logical dependencies.</blockquote><p>The solution presented in this post is more informal and simplified to make it accessible (Especially I’m occulting IO). Also I dont present the part of the author’s functional model of GUIs (maybe in another post).</p><p>The model described in the article builds on top of 3 concepts</p><ul><li><em>Getters </em>(Extractors in the paper) for retrieving some piece of state</li><li><em>Notifiers </em>abstract over change notification</li><li>Sources combine the 2 previous concepts to represent time varying state.</li></ul><h3>Getters</h3><p>A Getter is a function that takes no parameter and returns a value</p><pre>Getter a :: () -&gt; a</pre><p>I’m writing type annotations in a pseudo Haskell notation. The declaration above means that a Getter for a given type ais a function which takes nothing and return that type.</p><p>Example</p><pre>// message :: Getter String<br>const message = () =&gt; &#39;Hello world!&#39;</pre><pre>// scrollTop :: Element -&gt; Getter Number<br>function scrollTop(element) {<br>  return () =&gt; element.scrollTop<br>}</pre><pre>current value of `a`<br>var a = 10<br>// getA :: Getter Number<br>const getA = () =&gt; a</pre><p>Our abstraction defined. We should provide some way to make it composable using functions as we do with simple values.</p><p>We start with computations on a single value. Given a Getter a and a function f :: a -&gt; b, we&#39;ll derive a Getter b which will return f(a) if the original Getter returns a.</p><pre>// gmap :: ((a -&gt; b), Getter a), Getter b<br>function gmap(fn, getter) {<br>  return () =&gt; fn(getter())<br>}</pre><p>Note that gmap simply denotes function composition</p><pre>// compose :: ((a -&gt; b), (x -&gt; a)) -&gt; (x -&gt; b)<br>function compose(f, g) {<br>  return x =&gt; f(g(x))<br>}</pre><p>Just replace the x in the type annotation with ().</p><p>For example, given the current value of a DOM input, we’d like a Getter with the trimmed and upper-cased text</p><pre>// inputValue :: HTMLInputElement -&gt; Getter String<br>function inputValue(input) {<br>  return () =&gt; input.value<br>}</pre><pre>// getValue :: Getter String<br>const getValue = inputValue(document.getElementById(&#39;my-input&#39;))</pre><pre>function sanitizeText(text) {<br>  return text.trim().toUpperCase()<br>} </pre><pre>const getSanitizedText = gmap(sanitizeText, getValue)</pre><p>Of course we can write our Getter directly as () =&gt; domInput.value.trim().toUpperCase() but by doing this, we lose the advantage of composition. We&#39;ll see how later on the ‘Sources’ section.</p><p>To compose Getters we’ll define a gcombine function. Given 2 inputs Getter a and Getter b and a binary function f :: (a, b) -&gt; c. We&#39;d like to derive a Getter c whose value is f(a, b).</p><pre>// gcombine2 :: ((a, b) -&gt; c, Getter a, Getter b) -&gt; Getter c<br>function gcombine2(fn, getter1, getter2) {<br>  return () =&gt; fn(getter1(), getter2())<br>}</pre><p>As an example, given 2 Getters for 2 DOM inputs, we derive a Getter for their sums (I know I lack creative demos, this is just to illustrate)</p><pre>const getX = inputValue( document.getElementById(&#39;x-input&#39;) )<br>const getY = inputValue( document.getElementById(&#39;y-input&#39;) )</pre><pre>function sum(x, y) {<br>  return Number(x) + Number(y)<br>}</pre><pre>const getSumXY = gcombine2(sum, getX, getY)</pre><p>We can define gcombine3 or gcombine4 for combining with 3-ary or 4-ary functions. But let&#39;s just generalize to a variable number of parameters</p><pre>// gcombine :: ((...a) -&gt; b, ...Getter a) -&gt; Getter b<br>function gcombine(fn, ...getters) {<br>  return () =&gt; fn(...getters.map(g =&gt; g()))<br>}</pre><p><em>Note: We can make the </em><em>fn parameter itself a Getter to combine with dynamic functions.</em></p><p>And that’s it for Getters.</p><h3>Notifiers</h3><p>Next we’ll introduce <em>Notifiers</em>. Quoting the author</p><blockquote>value extraction is not enough; we also need to construct change notifiers. We will represent a notifier as the ability for clients to “subscribe” actions to be invoked whenever an event occurs.</blockquote><p>A Getter allows us to get a stable reference to some piece of state. While a Notifier informs us whenever this piece of state changes.</p><p>First let’s define some type signatures</p><pre>Listener a :: a -&gt; ()<br>Unsubscribe :: () -&gt; ()<br>Notifier a :: Listener a -&gt; Unsubscribe</pre><p>This may seem familiar if you’ve worked with Event Emitters. A Notifier for a given type a is a function which takes a listener for the same type and returns a function to unsubscribe the listener when invoked.</p><p>A simple exemple could be subscribing to DOM input changes</p><pre>function domNotifier(target, event) {<br>  return (listener) =&gt; {<br>    target.addEventListener(event, listener)<br>    return () =&gt; {<br>      target.removeEventListener(event, listener)<br>    }<br>  }<br>}</pre><pre>// inputChanged :: Notifier Event<br>const inputChanged = domNotifier(someDOMInput, &#39;change&#39;)</pre><pre>const unsubscribe = inputChanged(e =&gt; {<br>  console.log(&#39;Got a change event&#39;, e)<br>})</pre><p>As in the previous section, we define the map function. Given a Notifier a and a function f :: a -&gt; b, we&#39;ll derive a Notifier b. The resulting Notifier will notify f(a) whenever the original Notifier notifies a</p><pre>// nmap :: (a -&gt; b, Notifier a) -&gt; Notifier b<br>function nmap(fn, notifier) {<br>  return listener =&gt; {<br>    return notifier(a =&gt; listener(fn(a)))<br>  }<br>}</pre><p>Our implementation simply substitutes the given listener with another one that intercepts the reported event data, transforms it with the mapping function, and finally passes the transformed data to the original listener.</p><p>For example, we can transform inputChanged in our previous example, from a Notifier Event to a Notifier String by mapping it with a function that extracts the value from the DOM event.</p><pre>const targetValue = event =&gt; event.target.value<br>const inputValueChanged = nmap(targetValue, inputChanged)</pre><p>We’re not going to compose Notifiers like we did with Getters (using Applicative). Instead we opt for the merge operation. Given 2 Notifiers, we&#39;ll build a Notifier that notifies changes from both sources (merging 2 sources into one).</p><pre>// merge2 :: (Notifier a, Notifier b) -&gt; Notifier (a | b)<br>function merge2(notifier1, notifier2) {<br>  return listener =&gt; {<br>    // subscribes the passed listener to both notifers<br>    const unsubscribe1 = notifier1(listener)<br>    const unsubscribe2 = notifier2(listener)</pre><pre>    // result function unsubscribe also from both notifiers<br>    return () =&gt; {<br>      unsubscribe1()<br>      unsubscribe1()<br>    }<br>  }<br>}</pre><p>Similarly, we can extend the above definition to an arbitrary list of notifiers</p><pre>// merge :: (...Notifier a) -&gt; Notifier a<br>function merge(...notifiers) {<br>  return listener =&gt; {<br>    const unsubscribes = notifiers.map(<br>      notifier =&gt; notifier(listener)<br>    )<br>    return () =&gt; {<br>      unsubscribes.forEach(unsubscribe =&gt; unsubscribe())<br>    }<br>  }<br>}</pre><p>As an example, consider the classic up/down demo when we subscribe to clicks on 2 buttons Up and Down</p><pre>const btnUp = document.getElementById(&#39;btn-up&#39;)<br>const btnDown = document.getElementById(&#39;btn-down&#39;)</pre><pre>const upDown = merge2(<br>  nmap(() =&gt; &#39;Up&#39;, domNotifier(btnUp)),<br>  nmap(() =&gt; &#39;Down&#39;, domNotifier(btnDown))<br>)</pre><pre>upDown(type =&gt; console.log(&#39;Got a click on&#39;, type))</pre><p>And to complete we’ll define one more operator. We’ll call it Never. It simply represents a Notifier which doesn&#39;t report any change (We&#39;ll use it later to define constant sources of data). The implementation is just a noop function.</p><pre>// Never :: Notifier ()<br>const Never = () =&gt; {}</pre><p>Now that we have our ingredients, let’s get to the main stuff.</p><h3>Sources</h3><p>To represent sources of data that may change, we use a pair of Getter &amp; Notifier. The Getter allows us to extract the up-to-date version of the data while the Notifier notifies us when any change happens to that data.</p><pre>// simple factory function<br>function Source(getter, notifier) {<br>  return {<br>    getter,<br>    notifier<br>  }<br>}</pre><p>The simplest example of Sources is the constant Source whose data never changes</p><pre>// sconst :: a -&gt; Source a<br>function sconst(a) {<br>  return Source(<br>    () =&gt; a,  // always return the same data<br>    Never     // never report changes<br>  )<br>}</pre><p>Another example, we can represent the value of a text input as a Source which will report changes made by the user on every change event (or also input events)</p><pre>function inputValueSource(element, event) {<br>  return Source(<br>    () =&gt; element.value,<br>    domNotifier(element, event)<br>  )<br>}</pre><pre>const myInput = document.getElementById(&#39;my-input&#39;)<br>const myInputValue = inputValueSource(myInput, &#39;change&#39;)</pre><p>As we did previously. Let’s define the map function. Given a Source a and a function f :: a -&gt; b, we&#39;ll derive a new Source b whose Getter returns f(a) (whith the original Source&#39;Getter returning a).</p><pre>// smap ::  ((a -&gt; b), Source a) -&gt; Source b<br>function smap(fn, src) {<br>  return Source(<br>    gmap(fn, src.getter), // maps over the Getter<br>    src.notifier          // reuses the same Notifier<br>  )<br>}</pre><p>Our goal is to transform Source a to Source b given some function a -&gt; b. For example, imagine we have a source for a numeric value, and we want to get a source representing the double of that value.</p><pre>A :: Source Number<br>doubleOfA :: Source Number<br>doubleOfA = smap(x =&gt; x * 2, A)</pre><p>We want the Getter of our derived Source to always return the double of the value returned by the Getter of the original Source. That’s why in our implementation, we map the passed function over the Getter of the original Source.</p><p>Similarly, our new Source should report changes whenever the original Source reports changes itself. Since a change in the original Getter’s value will likely (but not necessarily) result in a change on the transformed value, we simply reuse the Notifier of the original Source.</p><p>To compose multiple Sources we’ll build on top the composition of its constituents. i.e. we compose input Sources by composing their Getters and Notifiers respectively.</p><p>We’ll start with binary functions: Given some input Sources Source a and Source b and a binary function f :: (a, b) -&gt; c, we&#39;ll derive a Source whose Getter returns f(a, b) (with the 2 input Sources Getters returning resp. a and b). Also, we want our new Source to report changes whenever <em>any</em> of the input Sources reports changes because a change on any input value will likely result in a change on the output value.</p><pre>// scombine2 :: ((a, b) -&gt; c, Source a, Source b) -&gt; Source c<br>function scombine2(fn, src1, src2) {<br>  return Source(<br>    gcombine2(fn, src1.getter, src2.getter),<br>    merge2(src1.notifier, src2.notifier)<br>  )<br>}</pre><p>The implementation compose 2 Sources by</p><ul><li>composing their Getters using the mapping function</li><li>merging their Notifiers to get a change notification whenever any of the input Notifiers reports some change.</li></ul><p>And similarly we define a generalized version which works with a variable number of parameters</p><pre>// scombine :: ((...a) -&gt; b, ...Source a) -&gt; Source b<br>function scombine(fn, srcs) {<br>  return Source(<br>    gcombine(fn, ...srcs.map(src =&gt; src.getter)),<br>    merge(...srcs.map(src =&gt; src.notifier))<br>  )<br>}</pre><p>Finally, we’ll define a react function (runDD in the paper) which will execute some action whenever the Source changes. In our implementation, the action will be passed the current value of the Source as a parameter</p><pre>// Action a :: a -&gt; ()<br>// react :: (Source a, Action a) -&gt; Unsubscribe<br>function react(src, action) {<br>  const listener = () =&gt; action(src.getter())</pre><pre>  // executes the action as initialization<br>  listener()</pre><pre>  // returns a function to unsubscribe the action<br>  return src.notifier(listener)<br>}</pre><p>Sources provide a low level and a generic abstraction upon which we can build higher level ones. But they come equipped with a solid compositional foundation (yes Math). You can define sources of multiple types (Mutable variables, Behaviors, Server data …) and combine them using the common combining method.</p><h3>Some Examples of Sources</h3><ul><li>Knockout/Mobx like observables</li><li>Redux Store state</li><li>Reactive Behaviors</li></ul><h4>Knockout/Mobx like observables</h4><p>We can define Sources that reflects values of mutable variables. We provide the initial value at the Source creation and expose an imperative set method to mutate the value inside the Source. Each change will propagate throughout all Sources which depend on the root Source.</p><p>We start by defining a simplified implementation of event emitters</p><pre>function Emitter() {<br>  <br>  let listeners = []</pre><pre>  return {<br>    subscribe(listener) {<br>      listeners.push(listener)<br>      return () =&gt; {<br>        listeners.splice(listeners.indexOf(listener), 1)<br>      }<br>    },</pre><pre>    emit(data) {<br>      listeners.forEach(listener =&gt; listener())<br>    }<br>  }<br>}</pre><p>Then our mutable Source instance</p><pre>function Mutable(seed) {</pre><pre>  const emitter = Emitter()</pre><pre>  const src = Source(<br>    () =&gt; seed,<br>    emitter.subscribe<br>  )<br>  // provide a method to mutate the state manually<br>  src.set = newValue =&gt; {<br>    seed = newValue<br>    emitter.emit()<br>  }</pre><pre>  return src<br>}</pre><p>Now we can create and combine them using the Source composition capability.</p><pre>const ma = Mutable(1)<br>const mb = Mutable(2)</pre><pre>const mc = scombine(<br>  (a, b) =&gt; a + b,<br>  ma, mb<br>)</pre><pre>react(mc, value =&gt; {<br>  console.log(&#39;c = &#39;, value)<br>})</pre><pre>ma.set(100)</pre><h4>Avoiding Glitches</h4><p>There is a little issue in the Mutable implementation above. Suppose we have this example</p><pre>const ma = Mutable(1)</pre><pre>// mb depends on ma<br>const mb = smap(<br>  a =&gt; a * 2,<br>  ma<br>)</pre><pre>// mc depends on both ma &amp; mb<br>const mc = scombine(<br>  (a, b) =&gt; a + b,<br>  ma, mb<br>)</pre><pre>react(mc, value =&gt; {<br>  console.log(&#39;c = &#39;, value)<br>})</pre><pre>ma.set(10)<br>/**<br>The console message is reported twice. Due to a redundant notification<br>=&gt; 30<br>=&gt; 30<br>**/</pre><p>When we set the value of ma the action registered in react gets executed twice. This happens because of our dependency chain</p><ul><li>mb depnds on ma</li><li>mc depends both on mb and ma</li></ul><p>Due to how scombine and merge are implemented we end up subscribing to the original source ma twice. The first time, react registers its listener to mb which simply registers it to ma, (remember smap reuses the notifier of the input Source), the second time it subscribes directly to ma. Because of this we get a redundant subscription and notification.</p><p>A simple solution is to prevent Emitter from registering the same listener twice. We can do this by replacing the internal array of listeners with a Set (a Set ensures that only one copy of the element is stored inside it)</p><pre>function Emitter() {<br>  let listeners = new Set()</pre><pre>  return {<br>    subscribe(listener) {<br>      listeners = listeners.add(listener)<br>      return () =&gt; {<br>        listeners = listener.delete(listener)<br>      }<br>    },</pre><pre>    emit(data) {<br>      listeners.forEach(listener =&gt; listener())<br>    }<br>  }<br>}</pre><p>A more general Solution (presented in the paper) will be making the notifier member of Source itself a Set. We can then define merge like an operation which merges together 2 Sets. react will subscribe to all elements in the final Set. Because the Set ensures uniqueness of elements inside it, any combined Source passed to react will have exactly one copy of each source notifier, even if we endup recombining the same source more than once.</p><h4>Redux Store’s state</h4><p>Defining a Source instance for Redux Stores is trivial, because we already have the required elements: a Getter and a Notifier.</p><pre>function reduxSource(store) {<br>  return Source(<br>    store.getState,<br>    store.subscribe<br>  )<br>}</pre><p>We can then combine multiple stores into one Source. The resulting Source could for example provides an aggregation of all the states of the combined stores</p><pre>const storeA = createStore(<br>  combineReducers({<br>    sliceOneA: ...,<br>    sliceTwoA: ...<br>  })<br>)</pre><pre>const storeB = createStore(<br>  combineReducers({<br>    sliceOneB: ...,<br>    sliceTwoB: ...<br>  })<br>)</pre><pre>const srcA = reduxSource(storeA)<br>const srcB = reduxSource(storeB)</pre><pre>const combinedSrc = scombine((stateA, stateB) =&gt; {<br>  return {stateA, stateB}<br>}, srcA, srcB)</pre><pre>/**<br>Will have a state shape of<br>{<br>  stateA: {<br>    sliceOneA: ...,<br>    sliceTwoA: ...<br>  },<br>  stateB: {<br>    sliceOneA: ...,<br>    sliceTwoA: ...<br>  }<br>}</pre><pre>Notifications will bubble up from both stores.<br>**/</pre><p>We can even combine Redux Sources with other types of Sources like Mutables.</p><h4>Reactive Behaviors</h4><p>Reactive Behaviors are like an hybrid between free Mutables and Redux encapsulated state. To create a Behavior, we need to provide a</p><ul><li>An initial value</li><li>A list of pairs (Notifier, reducer) // reducer :: (state, event) -&gt; state</li></ul><p>The Getter for the Behavior will first returns the initial value. But each time a Notifier in the list of pairs (Notifier, Reducer) reports some event we invoke the corresponding reducer with the current value of the Behavior and the reported event.</p><p>For example, here is the classic upDwon demo (the example is trivial but can be extended to handle more complex cases of incremental state)</p><pre>&lt;button id=up&gt;Up&lt;/button&gt;<br>&lt;button id=down&gt;Down&lt;/button&gt;<br>&lt;div id=count&gt;&lt;/div&gt;</pre><pre>const onUp = domNotifier(document.getElementById(&#39;up&#39;), &#39;click&#39;)<br>const onDown = domNotifier(document.getElementById(&#39;down&#39;), &#39;click&#39;)<br>const divCount = document.getElementById(&#39;count&#39;)</pre><pre>const count = Behavior(0,<br>  [onUp, (count, _) =&gt; count + 1],<br>  [onDown, (count, _) =&gt; count - 1]<br>)</pre><pre>react(count, value =&gt; {<br>  divCount.textContent = `Count = ${value}`<br>})</pre><p>A possible implementation of Behaviors on top of Sources</p><pre>function Behavior(seed, ...cases) {</pre><pre>  cases.forEach(([notifier, reducer]) =&gt; {<br>    notifier(event =&gt; {<br>      seed = reducer(seed, event)<br>    })<br>  })</pre><pre>  return Source(<br>    () =&gt; seed,<br>    merge(...cases.map(([notifier, _]) =&gt; notifier))<br>  )<br>}</pre><h3>Further developments</h3><p>Possible ideas</p><ul><li>scombine (and therefore gcombine) re-applies the function on each notification even if the data has not changed. We can memoize the combining function to avoid wasteful recomputations</li><li>Add support for dynamic dependencies: Right now, you have to provide the input sources to scombine at the invocation. Sometimes it&#39;s not possible to know in advance the list of dependencies (eg aSource containing an array of Sources). A possible solution could be declaring the notifier member of a Source itself as a Source. ie instead of Source a :: (Getter a, Notifier ()) we&#39;ll have instead Source a :: (Getter a, Notifier () | Source (Notifier ()) )</li><li>Define a Monad instance for Notifier (join, flatmap) to perform Side Effects</li><li>Connect Sources to React components</li></ul><p><a href="https://gist.github.com/yelouafi/63b2f31eacfd2d51c2d229bdbb1a3d0e">Gist containing the source code</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8fc1b15b75c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containment in React Components]]></title>
            <link>https://medium.com/@yelouafi/react-owner-ownee-relation-3b0fef7e12d7?source=rss-b6f1fc99587d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b0fef7e12d7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Yassine Elouafi]]></dc:creator>
            <pubDate>Fri, 21 Oct 2016 17:59:23 GMT</pubDate>
            <atom:updated>2019-09-19T11:08:59.799Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose we have this simple component</p><pre>function Greeting({name}) {<br>  return (<br>    &lt;h1&gt;Hello {name}!&lt;/h1&gt;<br>  );<br>}</pre><p>We want to show this component inside a box. The box will draw a selection outline around our component when the user clicks on it, and will toggle the selection state each time it&#39;s clicked.</p><p>First We’ll show the <em>direct</em> way</p><pre>class GreetingBox extends React.Component {</pre><pre>  constructor(props)  {<br>    super(props)<br>    this.state = { selected: false }</pre><pre>    this.toggleSelection = () =&gt; {<br>      this.setState( state =&gt; ({ <br>        selected: !state.selected <br>      }))<br>    }<br>  }</pre><pre>  render() {<br>    const style = {<br>      cursor: &#39;default&#39;,<br>      border: this.state.selected ? &#39;1px dotted black&#39;: &#39;none&#39;<br>    }<br>    return (<br>      &lt;div style={style} onClick={this.toggleSelection}&gt;<br>        &lt;Greeting name=&#39;World&#39; /&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><p>Of course, above there is an unnecessary coupling between GreetingBox and Greeting. A selection box is typically unaware of what’s inside it, and I guess this is a well known thing. But here I want to show another thing I noticed. it maybe something experienced React developers already know, but I couldn’t find any explicit mention to it in the the React docs (esp. performance related ones).</p><p>First let’s add a simple log statement inside our render methods</p><pre>function Greeting () {<br>  console.log(&#39;Greeting.render()&#39;)<br>  ...<br>}<br><br>class GreetingBox extends React.Component {<br>  ...<br>  render() {<br>    console.log(&#39;GreetingBox.render()&#39;)<br>    ...<br>  }<br>}</pre><p>And then render our application into a dom node (#app in our example)</p><pre>ReactDom.render(<br>  &lt;GreetingBox /&gt;,<br>  document.querySelector(&#39;#app&#39;)<br>)</pre><p>Now run this application and observe the console messages</p><blockquote><a href="http://jsbin.com/qagifi/edit?js,console,output">You can use this online demo</a></blockquote><p>You’ll see that each time you click on GreetingBox, Greeting&#39;s render method is being called. But this is natural, isn&#39;t it? GreetingBox.setState triggers a re-render of the component, which will trigger itself calling children&#39;s render method (unless shouldComponentUpdate prevents it).</p><p>Now let’s change our implementation of GreetingBox and make a generic container (not in the sense of Container/Smart vs Presentational/Dumb).</p><pre>class SelectableBox extends React.Component {<br>  ... <br>  render() {<br>    ...<br>    return (<br>      &lt;div style={style} onClick={this.toggleSelection}&gt;<br>        {this.props.children}<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><p>We made our box generic and unaware of its rendered content.</p><p>Let’s rewrite our application with the new implementation</p><pre>function App() {<br>  console.log(&#39;App.render()&#39;)<br>  return (<br>    &lt;SelectableBox&gt;<br>      &lt;Greeting name=&#39;World&#39; /&gt;<br>    &lt;/SelectableBox&gt;<br>  )<br>}</pre><p>Instead of an ad-hoc component GreetingBox, we&#39;re making our application by composing SelectableBox and Greeting. We&#39;re passing Greeting as the children property of of SelectableBox.</p><p>Now let’s re-execute the application</p><pre>ReactDom.render(<br>  &lt;App /&gt;,<br>  document.querySelector(&#39;#app&#39;)<br>)</pre><blockquote><a href="http://jsbin.com/dusenih/edit?js,console,output">You can use this online demo</a></blockquote><p>If you observe the console message you’ll see that this time the Greeting’s render method is no longer called when you click on the message. Even if the SelectableBox’s state is updated.</p><p>It may seem confusing to some people. Greeting is rendered <em>inside</em> SelectableBox and rendering the latter will naturally trigger a re-render of its children, unless we put a shouldComponentUpdate barrier. But apparently this wasn’t the case. Why ?</p><p>I think it’s due to 2 things</p><ul><li>A hard assumption that React makes about render methods being pure with regard to the Component’s props and state</li><li>and a special, and also lesser known, concept that React has: the Owner/Ownee relation in a rendered component tree (vs the traditional parent/child relation).<strong> <em>(Update: make sure to read comments made by Dan Abramov at the end of this post about this assumption)</em></strong></li></ul><blockquote>There is <a href="https://facebook.github.io/react/docs/multiple-components.html#ownership">a section in the React docs</a> that explains the relation. The section is brief but I think it’s clear enough.</blockquote><p>The important bits are:</p><blockquote>In React, <strong>an owner is the component that sets the </strong><strong>props of other components</strong>.</blockquote><blockquote>The owner-ownee relationship is specific to React, while the parent-child relationship is simply the one you know and love from the DOM</blockquote><p>Back to our example:</p><ul><li>the App component is the <em>owner</em> of both SelectableBox and Greeting because it sets their props in its render method.</li><li>the SelectableBox is the <em>parent</em> of Greeting because it renders it inside its proper render tree. SelectableBox doesn’t affect its children in any way but acts as a mere visual placeholder for it.</li></ul><p>As mentioned above, you may have thought that updating a component always triggers a re-render and reconciliation of its children but as it appears from our example, this only applies to owned components.</p><blockquote>I’m not sure how this is implemented under the hood. But one possible way (which React may or may not be using) is to perform some form of memoization on instances’s render method.</blockquote><blockquote>Since render methods are assumed to be pure (with regard to props and state), an update to a non owner component will not modify children’s props, so a memoized render will not actually invoke the instance’s render method but just return the latest cached result (last element returned by render). Reconciliation on this case will be very fast because we will have the same memory reference for both the old and the new element and can skip the much slower deep comparison process.</blockquote><p>In this case however we update App which is the Greeting&#39;s owner:</p><pre>class App extends React.Component {</pre><pre>  constructor(props)  {<br>    super(props)<br>    this.state = { dummy: 0 }</pre><pre>    this.updateState = () =&gt; {<br>      this.setState( state =&gt; ({ <br>        dummy: ++state.dummy <br>      }))<br>    }<br>  } </pre><pre>  render() {<br>    console.log(&#39;App.render()&#39;)<br>    return (<br>      &lt;div&gt;<br>        &lt;button onClick={this.updateState}&gt;<br>          Update App state<br>        &lt;/button&gt;<br>        &lt;SelectableBox&gt;<br>          &lt;Greeting name=&#39;World&#39; /&gt;<br>        &lt;/SelectableBox&gt;<br>       &lt;/div&gt;<br>    )<br>  }<br>}</pre><blockquote><a href="http://jsbin.com/sonori/edit?js,console,output">See what happens with this online demo</a></blockquote><p>If you click the ‘Update App state’ button and watch the console output, you will notice that updating App&#39;s state triggers a re-render of all its owned components (SelectableBox and Greeting).</p><p>Even if the passed props didn’t change (no props were passed toSelectableBox and a constant &#39;World&#39; is always passed to thename prop of Greeting), the render method of App constructs new SelectableBox and Greeting elements, which in turn triggers (I guess) the invocation of render methods on the corresponding Component’s instances. Here we need to optimize with the well known shouldComponentUpdate if want to prevent the unnecessary rendering.</p><p>I think this behavior is what sets React apart from other virtual DOM libraries. In a raw virtual DOM approach (the lib only provides abstraction for virtual nodes, diff and patch, but not for Components), there is only one relation: the parent/child, which typically reflects the real DOM hierarchy. Updating a virtual node will trigger the reconciliation of all its children, because the lib has no knowledge of data flow dependencies (who’s responsible of setting props on a virtual node). To optimize, we need to use an explicit optimization/memoization (like <em>thunks</em> in Snabbdom)</p><p>In some situation this can be really crucial for the application’s performances. Imagine that our top level App renders an expensive part of its tree inside a Dockable container.</p><pre>&lt;App&gt;<br>  &lt;Dock&gt;<br>    ... some component tree we need to dock<br>  &lt;/Dock&gt;<br>  ... some other component tree here<br>&lt;/App&gt;</pre><p>Suppose the Dock component provides some UI to allow adjusting its width via mouse dragging. In a raw virtual dom approach, each mouse movement will cause a reconciliation of the entire Dock&#39;s children tree unless you put some explicit/manual optimization barrier.</p><p>However in React, mouse movements will only trigger a reconciliation on the Dock component but not on the expensive child subtree because Dock doesn&#39;t own it. And all this is handled automatically by the underlying React model, no manual or explicit optimization is required.</p><p>As a side note, I tried the above example with <a href="https://github.com/developit/preact">Preact</a> which is a popular alternative implementation with a similar React api.</p><blockquote><a href="http://jsbin.com/vimana/edit?js,console,output">Online demo with preact</a></blockquote><p>You’ll notice that when you click on the message, triggering an update on SelectableBox, The Greeting render method is called even if SelectableBox doesn’t own it. So it appears that Preact doesn’t have support, at the time of this writing, of the Owner/Ownee relation.</p><blockquote><strong>Update</strong>, Dan Abramov made some comments about the Owner/ownee assumption</blockquote><h3>Dan Abramov on Twitter</h3><p>@YassineElouafi2 I don&#39;t think it&#39;s owner/ownee. (We&#39;re actually trying to kill the tracking of current owner because it causes issues.)</p><h3>Dan Abramov on Twitter</h3><p>@YassineElouafi2 Most likely it&#39;s because this.props.children is referentially equal between renders since App wasn&#39;t re-rendered.</p><h3>Dan Abramov on Twitter</h3><p>@YassineElouafi2 React bails out if the elements are referentially equal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b0fef7e12d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elm Architecture/Side Effect examples with Snabbdom and JSX]]></title>
            <link>https://medium.com/@yelouafi/elm-architecture-side-effect-examples-with-snabbdom-and-jsx-3732219d9995?source=rss-b6f1fc99587d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3732219d9995</guid>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[virtual-dom]]></category>
            <dc:creator><![CDATA[Yassine Elouafi]]></dc:creator>
            <pubDate>Sat, 21 Nov 2015 06:48:25 GMT</pubDate>
            <atom:updated>2015-11-23T11:37:42.142Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nyRd2VStnN1J6zHB_NMwfw.jpeg" /><figcaption>Photo ©<a href="http://somadjinn.deviantart.com/"> Nicolas Raymond (aka somadjinn)</a></figcaption></figure><h3>Elm Architecture &amp; Side Effects: example with Snabbdom/JSX</h3><p><a href="https://medium.com/@yelouafi/react-less-virtual-dom-with-snabbdom-functions-everywhere-53b672cb2fe3#.3k1tbd44a">In a previous post</a> we saw how to write web applications based on the Elm architectural pattern (using plain JavaScript and <a href="https://github.com/paldepind/snabbdom">Snabbdom</a> for Virtual DOM rendering). The main benefit of Elm architecture being that we can describe the application logic as a set of pure functions.</p><p>This article treats the next logical step: how to deal with Side Effects in the pure Elm model : server API calls, Asynchronous Actions …</p><h3>The Login example</h3><p>During this post we’ll develop a simple login application : the user is provided with a login form when he must enter a username and a password. Then the entered credentials are validated against a remote API, if the login is successful the user is redirected either to an admin page if he has the admin role or a guest page otherwise.</p><p>We’ll start with a pure version without side effects, then we’ll enhance the application by introducing side effects and a nested hierarchy of components.</p><p>To stay focused the API will be mocked by a simple local timeout-ed function.</p><blockquote><a href="https://github.com/yelouafi">Full sources of this example are here</a></blockquote><h3>The Setup</h3><p>To start our project we need the following libs:</p><ul><li>snabbdom : for Virtual DOM creation and patching</li><li>snabbdom-jsx : to generate Snabbdom virtual nodes using JSX</li><li>union-type: to represent Actions</li></ul><p>We’ll also need babel to compile ES2015 and JSX code into compatible JavaScript code. To build the browser bundle, you can either use Browserify or Webpack; in this post i’ll use the first one.</p><p>You can use the following into your package.json file to get things up quickly</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b06bb0acd4b4069a9f9cd6a604f1f9df/href">https://medium.com/media/b06bb0acd4b4069a9f9cd6a604f1f9df/href</a></iframe><p>then run ‘<em>npm install</em>’ to pull all dependencies</p><p>To host the JS application w’ll use this index.html file in the root of our example directory</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe44fa9c1b401c919b46c97938f73999/href">https://medium.com/media/fe44fa9c1b401c919b46c97938f73999/href</a></iframe><p>You can get the ‘style.css’ file <a href="https://github.com/yelouafi/elm-examples-js/blob/master/style.css">from here</a>.</p><p>Finally create a ‘js’ sub-directory. All our application code will go inside it. The final directory layout should look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*JDKhizmuPvlH9sD91pBh8A.png" /></figure><p>Et voilà! We’re ready to start</p><h3>The Login Component : iteration 1</h3><p>Create a Login.js file inside the js directory (from now on all JavaScript files must be put here). Here is our first version</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ecab17031b356d72bee667ffbd66afe/href">https://medium.com/media/3ecab17031b356d72bee667ffbd66afe/href</a></iframe><p>Our component defines 2 functions, ‘init’ which returns the initial state and ‘view’ which constructs a virtual node from a given state. For now, ‘Login’ is passive and doesn’t fire any action so we don’t have Actions or an ‘update’ function. All we do is showing data we get from the input state.</p><p>To bootstrap our application. Create a ‘main.js’ file then copy the following content</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fc0173001116a32fbb030281a924ef2/href">https://medium.com/media/8fc0173001116a32fbb030281a924ef2/href</a></iframe><p>The main module connects the component to the real DOM via the ‘dispatch’ function and continually reacts to all state changes by constructing new virtual nodes then patching the real DOM with them.</p><p>All we have to do now is</p><pre>npm run build</pre><p>It should compile all JavaScript files in the js directory and generate a ‘build.js’ file in the root of the example directory. Now open the index.html in the browser and normally you should have something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*PQjqXE7xsZJLNis0vp7ZCQ.png" /></figure><blockquote>If something goes wrong, let me a comment or create an issue in the GitHub repository.</blockquote><h3>The Login Component : iteration 2</h3><p>Now let’s add some action. First we’d like to save the user input into our state. We’ll also add a status message below the button, when the user submits the form, we’ll show the entered credentials in the status message. Later we’ll use it to show error messages.</p><p>Below the modifications to our code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48a1499d52e596eb0134ef42ebbb585e/href">https://medium.com/media/48a1499d52e596eb0134ef42ebbb585e/href</a></iframe><p>So here is what we did:</p><ol><li>We added 3 actions, 2 to get the ‘name’ and ‘password’ inputs, and one to react to the submit event of the form.</li><li>Since our data model has changed, the ‘init’ function also initializes the status message with an empty string.</li><li>We added 2 event handlers to hookup user events (see below)</li><li>updated the view : we added the status message and connected DOM events to our event handlers</li><li>Handled the actions in an ‘update’ function by setting the appropriate field (using the awesome (…) spread ES7 syntax thanks Babel!).</li></ol><p>‘onInput’ is a<em> </em>Higher Order Function, it takes an action, a dispatcher and returns another function : this is the real event handler that takes the input event, extracts the input string from event.target and then calls dispatch with that result.</p><p>In the view each input field creates its appropriate event handler by providing its particular action to the Higher Order Function ‘onInput’. This way we don’t have to create an event handler for each input for our view, especially, if you have a bunch of input fields in your form. Just one parametrized function to rule them all.</p><p>Actually, we can do better than that. Since we’ll likely need to extract the user input from event.target quite a lot, let’s create a helper function for that. Create a ‘helpers.js’ file and add the following function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/367cd555b8f744bcbf5b65f166d1140a/href">https://medium.com/media/367cd555b8f744bcbf5b65f166d1140a/href</a></iframe><p>Some of you may have already guessed. For ‘pipe’ it’s just function composition but in the other sens : take an input and send it through a pipeline of functions. Much like node pipes</p><p>Now back to the Login.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4f796b3d87266f50dfad4d204c1c183/href">https://medium.com/media/f4f796b3d87266f50dfad4d204c1c183/href</a></iframe><p>This is surely much better. Our event handlers are directly created by the pipe function. The event object travels through a set of pure functions until it reaches the dispatch callback.</p><p>‘onSubmit’ is another Higher Order Function (or a curried function if you like) which returns the form submit handler. It fires the Login action and do some necessary dirty stuff to prevent the browser from refreshing the web page.</p><p>That’s it, hit ‘npm run build’ again and refresh your browser page. Enter some data in the form and hit RETURN or click the Submit button. Normally you should see the entered data below the button.</p><p>Now let’s get to the dirty stuff : Side effects.</p><h3>The Login Component : iteration 3</h3><p>We’ll now make our Login a bit more realistic. Submitting the form should trigger some API call to validate the entered credentials, and get the response : for now we’ll just show a success or an error message. Later we’ll see how to redirect to an appropriate page on a successful login.</p><p>We’ll mock our API call with a simple local function using setTimeout, this way we can test our code locally without need to create a server side code.</p><p>Create an ‘api.js’ file with the following content</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ee03ffa3eb28c1115cb6db0f5a5b59d/href">https://medium.com/media/0ee03ffa3eb28c1115cb6db0f5a5b59d/href</a></iframe><p>For our testing purpose, a simple array will be sufficient. The exported function delays the response by 200ms to simulate a server call.</p><p>Now to the real question.</p><blockquote>When and where should we make the API call ?</blockquote><p>Well, as it turns out, there can be multiples answers.</p><p>In this post and the followings, w’ll expose 3 possible solutions</p><ol><li>Make the API call directly in the event handler</li><li>The standard Elm solution : changes the signature of the ‘update’ function to make it return the desired Side Effect (update : (state, action) → (state, Effect).</li><li>The third is inspired by <a href="https://github.com/rackt/redux/issues/891">this interesting post on the Redux Github site</a>. And tries to address an issue we’ll see with the Elm approach.</li></ol><p>Actually, all the 3 solutions share a common pattern, a side effect (like an asynchronous call) commonly involves 3 actions.</p><ol><li>A start action, before we trigger the side effect. In response to this action, the update function can react by setting some pending flag to show some spinner or loading indicator for example.</li><li>An outcome action, when the side effect is carried out and we get an eventual response : either a success or an error. So we’ll have to create a separate action for each possible outcome.</li></ol><h3>Login Component : Iteration 4</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7abe5cf47b142cb0705f77c817d576bb/href">https://medium.com/media/7abe5cf47b142cb0705f77c817d576bb/href</a></iframe><p>First, the Login action has been split into 3 actions as we described above : a start action and 2 possible outcomes.</p><p>Next, the onSubmit is called now with the current state as an additional parameter. Then both state and dispatch are passed down to the ‘doLogin’ function which triggers the API call.</p><p>doLogin first fires the start action, which is handled by update to display the “Please wait…” status message. Then makes the API call which returns a promise : either resolved with the success message or rejected with the login error. The promise response is handled by firing the appropriate outcome action. Which in turn is handled by update to notify the user via the status field.</p><p>This method has the advantage of being simple. It doesn’t add much boilerplate to our component while still keeping the update free of side effects. We’ll see next how this method fit in a nested hierarchy.</p><h3><strong>The App component</strong></h3><p>We’ll now expand our requirements : instead of showing a success login message. We’ll redirect the user to an appropriate page.</p><p>Create a new file App.js to hold the content of our new component.</p><p>We’ll go with the content step by step. First we define the state shape and its actions</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbda8a28adf2adc0dd26500710ca5af6/href">https://medium.com/media/bbda8a28adf2adc0dd26500710ca5af6/href</a></iframe><p>Our state holds a page dictionary, the current user name, the current page and, since the App component will embed the Login component, we maintain the current Login state.</p><p>We define 2 actions : one for switching to the appropriate page once we get a successful login and another to route Login Actions to their destination.</p><p>Next the view function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce2df58ddc6b5bfb67fa223966485bcf/href">https://medium.com/media/ce2df58ddc6b5bfb67fa223966485bcf/href</a></iframe><p>If the user has been successfully logged in, we show the appropriate page (Guest or Admin). Otherwise we show the Login page. Note how we pass onLogin callback : the Login component will call this function in the case of a successful login with the user name. onLogin, in turn, fire the ShowPage action passing it the same username.</p><p>The update function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/004d4410a92dc7afc0e0d62b7baf1204/href">https://medium.com/media/004d4410a92dc7afc0e0d62b7baf1204/href</a></iframe><p>ShowPage is simply handled by setting the user name in the state. As we saw in the view, the user name will be used as a key to access the appropriate page from the pages dictionary.</p><p>UpdateLogin handler simply routes the inner action to Login and save its new returned state.</p><p>We’ll still have to define the code for the Admin and Guest pages. For our example, they are simple passive views that display the current user</p><p>Admin.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89d19ddb327fb1b4b6bcc336a4e7d917/href">https://medium.com/media/89d19ddb327fb1b4b6bcc336a4e7d917/href</a></iframe><p>Guest.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66b7e6fc6327af359494a0078c16452a/href">https://medium.com/media/66b7e6fc6327af359494a0078c16452a/href</a></iframe><p>And don’t forget to update the code for the Login component</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe1fe95e30ef71e1e1f99ffa1cae1de2/href">https://medium.com/media/fe1fe95e30ef71e1e1f99ffa1cae1de2/href</a></iframe><p>And that’s it! we can finally hit npm run build to check the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*0ya0_JWyJT3SfdOeyuULRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*MqCXxvigyGWw-6DHWdSsKw.png" /></figure><p>And voilà! You have now a skeleton code for a simple router : You can enhance it for example to make the App component route actions for Admin and Guest. Thus allowing the child pages to be full reactive components (hint: add currentState field and an UpdatePage action). You can also hook up to the hashchange or popstate event of the window to trigger the ShowPage Action.</p><p>I’m going to stop here to get some sleep. Next post we’ll see the Elm solution to address side effects. Good night.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3732219d9995" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React-less Virtual DOM with Snabbdom :]]></title>
            <link>https://medium.com/@yelouafi/react-less-virtual-dom-with-snabbdom-functions-everywhere-53b672cb2fe3?source=rss-b6f1fc99587d------2</link>
            <guid isPermaLink="false">https://medium.com/p/53b672cb2fe3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[virtual-dom]]></category>
            <dc:creator><![CDATA[Yassine Elouafi]]></dc:creator>
            <pubDate>Tue, 28 Jul 2015 17:20:49 GMT</pubDate>
            <atom:updated>2016-07-05T10:10:36.200Z</atom:updated>
            <content:encoded><![CDATA[<h2>functions everywhere!</h2><p>React was a true addition to the JavaScript community. While one can find JSX — the HTML like syntax inside JavaScript — controversial. It is not the same for the Virtual DOM concept.</p><p>For the non familiar, Virtual DOM is a simplified memory representation of the real DOM state at a certain moment. The idea is : instead of directly updating the real DOM with imperative statements, you build a virtual DOM<em> </em>each time your UI state changes, and the underlying library updates the physical DOM accordingly</p><p>It’s important to note that the update operation doesn’t replace the whole DOM tree (like setting innerHTML with an HTML string), but only replaces the parts of the DOM that actually changed (modify Node properties, adding a child element…). i.e. <em>incremental updates</em> are inferred by <em>diffing</em> the old and the new Virtual DOM versions., then <em>patching</em> the real DOM to reflect the new version.</p><p>The Virtual DOM concept has been often emphasized for its speedy performance. But there is also an equally important — if not more important — property. The concept makes it possible to represent the UI as a function of its state. This makes it possible to explore new ways of writing web applications.</p><p>In this post we examine how the concept of Virtual DOM fits in a web application. W’ll start by simple examples then present an architecture to write virtual DOM based applications (hint: if you love pure functions, you won’t be deceived).</p><p>For that, we will opt for a standalone and plain JavaScript (no JSX) virtual DOM library, because we need to examine the smallest basic puzzles.</p><p>There are a few good standalone virtual DOM libraries around, for my post i will use snabbdom (<a href="https://github.com/paldepind/snabbdom">paldepind/snabbdom</a>), a small lib written by Simon Friis Vindum. But the examples can be implemented in any other similar lib like the Matt Esch’s <a href="https://github.com/Matt-Esch/virtual-dom">virtual-dom</a>.</p><h3>Quick snabbdom tutorial</h3><p>Snabbdom is provided as a set of CommonJs modules. So we need a client side module bundler like browserify or webpack.</p><p>First let’s examine how to bootstrap a basic application</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/911490ac5c55cf1f9f0b1b76c40caff4/href">https://medium.com/media/911490ac5c55cf1f9f0b1b76c40caff4/href</a></iframe><p>Above we ‘init’ the core snabbdom module with a set of <em>extensions</em>. In snabbdom, functionalities like toggling classes, styles and even setting properties on DOM elements are delegated to separate modules. For our case, we will just use the default modules.</p><p>The core module exposes only one function ‘patch’, which is returned by the init method. We use it to create the initial DOM as well as updating it later.</p><p>Here is what a basic Hello example looks like in snabbdom</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/899955b737b9440ece0ba22e94b9f071/href">https://medium.com/media/899955b737b9440ece0ba22e94b9f071/href</a></iframe><p>‘h’ is a helper function to create <em>virtual nodes</em>. W’ll discover the usage in the rest of this post, for now just remember it takes 3 inputs:</p><ol><li>a selector like ‘‘div#id.class’</li><li>an optional data object which specifies properties of the virtual node (class, styles, events …) as w’ll see later.</li><li>Optionally, a string or an array of child virtual nodes.</li></ol><p>The first time, patch expect a <em>placeholder </em>DOM element and an initial virtual node. It then creates the initial DOM tree that mirrors the virtual one. In subsequent calls, we provide it with the previous and the new virtual nodes. It then <em>diffs </em>the 2 virtual nodes and <em>patches </em>the DOM with the necessary modifications to take it into a new state that mirrors the new virtual representation</p><p>In order to get things up quickly, I created a GitHub repository with the all basic stuff to start right away. So the first step is to clone the repository at (<a href="https://github.com/yelouafi/snabbdom-starter">yelouafi/snabbdom-starter</a>). After that install the dependencies with ‘npm install’. The kit uses Browserify for browser bundling, Watchify for automatic rebuilds on file change, and Babel to allow us writing nice ES6 code and transpile it to ES5 compatible code.</p><p>After installing type</p><pre>npm run watch</pre><p>This will start the Watchify module, which will create the browser bundle ‘build.js’ inside the ‘app’ folder. The module will also watch for changes we make in JavaScript files and rebuild the bundle automatically (for manual builds you can type ‘npm run build’).</p><p>To run the application, open the ‘app/index.html’ file in the browser. Normally, you should see a ‘Hello world’ message on the screen.</p><p>All the examples w’ll see in this post can be found on the GitHub repo, each example is implemented in a specific branch, w’ll link to each branch throughout the post; the README file of the repo contains links to all branches.</p><h4>A dynamic view</h4><blockquote>Sources for this example in the <a href="https://github.com/yelouafi/snabbdom-starter/tree/dynamic-view">dynamic-view branch</a></blockquote><p>To highlight the dynamic aspect of the Virtual DOM, w’ll build a very simple clock. Change ‘app/js/main.js’ as below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64d32da487e4d9ef5be36152698705b9/href">https://medium.com/media/64d32da487e4d9ef5be36152698705b9/href</a></iframe><p>The virtual node construction has been delegated to a separate function ‘view’, which takes as input the current state (the current date).</p><p>The example illustrates a typical pattern in virtual DOM based applications. At the very low level, the application behavior consists of constructing new virtual trees successively at different moments of interest (timer, user events, server events…) and then patching the actual DOM with the changes compared to the latest virtual node. In our example, we construct a new virtual tree every second and update the DOM with it.</p><h4>Event reactivity</h4><blockquote>Sources for this example are in the <a href="https://github.com/yelouafi/snabbdom-starter/tree/event-reactivity">event-reactivity branch</a></blockquote><p>The next example introduces event handling through a basic greeting app</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58a6ec801bb034ec68640ff02ae2fe2b/href">https://medium.com/media/58a6ec801bb034ec68640ff02ae2fe2b/href</a></iframe><p>In snabbdom, we set element’s properties through the ‘props’ object, which get handled by the ‘props’ module. Similarly we set event listeners through the ‘on’ object which get handled by the ‘eventlisteners’ module.</p><p>In the above example, the ‘update’ function plays the same rule as ‘setInterval’ from the previous example : it constructs a new virtual tree, using the data extracted from the incoming event, then calls patch to update the DOM with the new created tree.</p><h3>Structuring complex applications</h3><p>The benefit of using a standalone virtual DOM library is that we become free to structure our application the way we like. You can adopt the old good MVC pattern, or opt for a ‘more modern’ architecture like Flux.</p><p>In this post i’ll present a less-known architectural pattern I’ve encountered in <a href="http://elm-lang.org/">Elm</a> (an FP language that compiles to JavaScript). The pattern is known among Elm developers as <a href="http://elm-lang.org/guide/architecture">Elm Architecture</a>, so w’ll stick to that name in the rest of this post. The main advantage is that it allows us to write the whole application as a set of pure functions.</p><p>But before, w’ll take a moment to reason about the overall behavior of our example above. In this process w’ll take some inspiration from <a href="https://www.youtube.com/watch?v=1zj7M1LnJV4">this excellent talk of André Staltz’s</a>.</p><h4>The main loop</h4><p>Let’s examine the overall process of the last example :</p><ol><li>evaluate the ‘view’ function with an initial state and construct our first virtual node. Within the ‘view’ function, a listener is attached to the ‘input’ event of the text input</li><li>patch the DOM with the new virtual node; attaching BTW the input event listener to the real DOM</li><li><em>waiting for user action : ticktock, ticktock…</em></li><li>the user finally types something, triggering the input event which calls the ‘update’ function</li><li>within ‘update’ we update the state (by constructing a new one)</li><li>we evaluate again the view function, passing it the new state constructed by the handler (same as step 1)</li><li>calling ‘patch’ again will repeat the above process again (same as step 2)</li></ol><p>The steps above describe a cyclical process. By getting rid of the implementation details we can establish an abstract sequence of function calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*A8VYQeV7MOWEzJslNjZehg.png" /></figure><p>‘user’ is an abstraction of user interactions. What we get is a circular sequence of function calls. Note that the ‘user’ function is <em>asynchronous</em>, otherwise w’ll have an infinite recursion.</p><p>Let’s turn the above process into real code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a32518d0d42c8b3369b48d33da74f3d/href">https://medium.com/media/7a32518d0d42c8b3369b48d33da74f3d/href</a></iframe><p>The ‘main’ function mirrors the cyclic process described above : given an initial state (our initial data), a DOM element and a <em>top component</em> (a pair view+update), ‘main’ evaluates the top component’s view function to construct a new virtual node from the current state, then patches the DOM with that virtual node.</p><p>Note the parameters passed to the ‘view’ function : first the <em>current </em>state and second the <em>main event handler : </em>a callback that handles events from the generated view. The handler is responsible for constructing a new state for the application and restarting the UI cycle with the new data (state + virtual node).</p><p>Construction of the new state is delegated to the top component’s ‘update’ function which is a simple (and pure) function : at each moment, given a current state and a current program input (event/action), it returns a new state for our application.</p><p>Note also that — beside the side effect in the patch method call — the main function has no mutated state.</p><p>The main function is somewhat similar to the ‘main’ event loop of low level GUI frameworks. The point here is<em> to take back the control over the UI event dispatching process</em> : in its actual state, the DOM API forces us into an Event Driven paradigm by adopting the Observer pattern. But we don&#39;t want to use the Observer pattern here as w’ll see in a moment.</p><h4>Elm architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*V4VKLsiO7cfCuf0nlgBoxA.png" /></figure><p>In an Elm-architecture based program, the basic building blocks are a set of modules, or, let’s say components. Each component has 2 basic functions : ‘update’ and ‘view’, along with a specific data contract : the ‘model’ type owned by the component and a set of actions that updates instances of that model.</p><ol><li>‘update’ is a pure function that takes 2 arguments : the current state which is an instance of the ‘model’ owned by the component and the current ‘action’ which describes the update operation that needs to take place. It returns a new ‘model’ instance.</li><li>‘view’ takes also 2 inputs : the current ‘model’ instance and an <em>event channel</em> which can be any mechanism by which events are propagated, in our examples w’ll use a simple callback function (the ‘handler’ argument). The function then returns a new virtual node that will get applied to the real DOM.</li></ol><p>As said above, Elm architecture walks away from the traditional Observer pattern that characterize typical event driven programs. Instead, the architecture favors a centralized model of dispatching (like in React/Flux), where any event : 1- <em>bubbles up</em> to the <em>top component</em>, 2- then <em>tunnels down</em> through a tree like hierarchy of components. During this phase, a component can choose to handle the action itself and/or forwards it to one or all of its children.</p><p>Another key property of the architecture is that the entire program state is held into one big data object. And each component in the tree is responsible for passing its children the part of state they own (w’ll see a concrete example of that).</p><p>In our demonstration w’ll use the same examples as in the Elm website as they perfectly illustrates the pattern.</p><h4>Example 1 : a basic counter</h4><blockquote>Sources for this example are in the <a href="https://github.com/yelouafi/snabbdom-starter/tree/counter-1">counter-1 branch</a></blockquote><p>The counter component is defined in its own module ‘counter.js’</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d9c787c28f614ae4e7af0728d37e398/href">https://medium.com/media/4d9c787c28f614ae4e7af0728d37e398/href</a></iframe><p>The counter component is defined by the following properties</p><ol><li>Model : a simple ‘Number’</li><li>View : provides the user with 2 buttons in order to increment/decrement a counter , and a text that shows the current count.</li><li>Update : sensible to 2 actions : INC and DEC that increments or decrements the counter value.</li></ol><p>The first thing to note is that the view/update are both pure functions, they have no dependency on any external environment besides their input. The counter component itself doesn’t hold any state or variable, it just describes how to construct a view from a given state, and how to update a given state with a given action. Thanks to its purity, the counter component can be easily plugged into any environment that is able to supply it with its dependencies : a state (number) and an action.</p><p>Second note, the ‘handler.bind(null, action)’ expression on the click event listener for each button. We are translating the <em>raw user event</em> (mouse click) into <em>a meaningful action</em> to our program (Increment or Decrement). Using ES6 symbols is better than raw strings (avoids collisions in action names), but w’ll see later a better solution provided by the so-called <em>union types</em>.</p><p>To see how our component can be tested; here is an example using the ‘tape’ testing library</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf62b5078d8e6f6aaa2dfe06bca76fdb/href">https://medium.com/media/bf62b5078d8e6f6aaa2dfe06bca76fdb/href</a></iframe><p>You can run the test using ‘babel-node’ command</p><pre>babel-node test/counterTest.js</pre><h4>Example 2: a pair of counters</h4><blockquote>Sources for this example are in the <a href="https://github.com/yelouafi/snabbdom-starter/tree/counter-2">counter-2 branch</a></blockquote><p>W’ll follow the same path as in Elm tutorial and augment slightly the counter example, w’ll now have 2 counters. Moreover, w’ll provide also a ‘reset’ button to reset both counters to ‘0’;</p><p>First, we have to modify our counter component to provide support for the reset operation. For that w’ll introduce a new function ‘init’ whose role is to construct a new fresh state (a count) for the counter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d45c9dfc3267c9fce54056f4f76cccc7/href">https://medium.com/media/d45c9dfc3267c9fce54056f4f76cccc7/href</a></iframe><p>‘init’ can be very useful in many situations. For example, initializing the state with data from the server or the local storage. It can also create a rich data model from a plain JavaScript object (e.g. enriching the plain object with some prototype properties and methods).</p><p>‘init’ is different in purpose from ‘update’ : while the latter derives a new state from a state and an action that updates that state, the former construct a new fresh state, optionally from some input (default value, server data …etc) , and totally ignores the previous state.</p><p>Second, w’ll have to add another component that will manage the 2 counters. We implement the code in a separate module ‘twoCounters.js’.</p><p>First we need to define our model and its associated set of actions</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2a605ed90e83f5f988e8673765ee602/href">https://medium.com/media/f2a605ed90e83f5f988e8673765ee602/href</a></iframe><p>The model exports 2 properties: ‘first’ and ‘second’ to hold the states of the 2 counters. We define 3 actions on : the first reset both counters to ‘0’. W’ll see the use of the 2 others in a moment.</p><p>The component has also an ‘init’ method to create a state from scratch</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bca72145d0c2c0518c5e60175e58b539/href">https://medium.com/media/bca72145d0c2c0518c5e60175e58b539/href</a></iframe><p>The view function is responsible for rendering the 2 counters as well as providing the user with a button to reset them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/146a24c9d94bac7c1b99633fb732f93c/href">https://medium.com/media/146a24c9d94bac7c1b99633fb732f93c/href</a></iframe><p>The thing to note is the 2 parameters passed to the child views:</p><ol><li>Each view gets its relevant part (model.first/model.second) of the parent state.</li><li>The dynamic handler parameter that’s passed down to the children’s views : For example, an action triggered from the first child counter will be wrapped in an ‘UPDATE_FIRST’ action, so when the parent’s update function is invoked, w’ll be able to forward the original action (stored in the ‘data’ attribute) to the correct counter.</li></ol><p>The rest of the code implements the update function and exports the component’s properties</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a084eb107ce06b68f60feaaf0b0fc38/href">https://medium.com/media/9a084eb107ce06b68f60feaaf0b0fc38/href</a></iframe><p>The update function handles 3 actions:</p><ol><li>the RESET action ‘init’ each counter to its default state.</li><li>the UPDATE_FIRST and UPDATE_SECOND are, as we just saw, wrappers around a counter action. The function forwards the wrapped action to the concerned child counter along with its specific state.</li></ol><p>Note the use of {…model, prop: val }; we are using the <a href="https://github.com/sebmarkbage/ecmascript-rest-spread">ES7 object spread properties</a> (like Object.assign) which always returns a new extended instance. We never modify the state passed in the argument but always returns a new state object with the relevant modifications. This is important to ensure the purity of the update function.</p><p>The rest of the code in ‘main’ simply invokes the top component with an initial state</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b72b6c991d891755f53e5046b1ccc757/href">https://medium.com/media/b72b6c991d891755f53e5046b1ccc757/href</a></iframe><p>The code of ‘twoCounters’ illustrates the typical pattern in an application with nested components :</p><ol><li>The components of an application are organized in a tree like hierarchy.</li><li>the main function invokes the top component’s view function with the global application state as parameter (and also the main handler).</li><li>When rendering its view, each parent invokes the children’s view functions, passing them the relevant parts of the state.</li><li>views translates raw DOM/user events into <em>actions </em>meaningful to the application.</li><li>actions triggered from child components <em>bubbles up</em> through parents up to the top component. Unlike the DOM event bubbling, a parent can not handle the action in this phase. All it can do is adding information to the triggered action (see next).</li><li>During the bubbling phase, the parent view function may intercept actions from its children in order to augment them with the needed information; typically information needed to identify the originating child when dispatching actions to the children.</li><li>The action ends up in the main handler, which will triggers the dispatching phase by invoking the top component’s update function.</li><li>each parent’s update function is responsible of dispatching the action to its children’s update functions.Typically using the information added during the action bubbling phase.</li></ol><h4>Example 3 : A list of counters</h4><blockquote>Sources for this example are in the <a href="https://github.com/yelouafi/snabbdom-starter/tree/counter-3">counter-3 branch</a></blockquote><p>Following the same path of Elm tutorial, w’ll expand further our example to manage an arbitrary list of counters. W’ll also provide the user with buttons to add new counters as well as remove existing counters.</p><p>The code for the ‘counter’ component will remain the same. W’ll have also to define a component ‘counterList’ to manage the array of counters.</p><p>As usual, we start by defining the model, the set of associated actions</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53b7451a15bd7199f57862b6983e960b/href">https://medium.com/media/53b7451a15bd7199f57862b6983e960b/href</a></iframe><p>The component’s model defines 2 properties</p><ol><li>a list of pairs (id, counter), the ‘id’ property plays the same role as the properties ‘first’ and ‘second’ in the previous example; it’ll allow the component to uniquely identify each child counter.</li><li>a ‘nextID’ property to maintain an auto-increment value, we will use this value to assign new IDs to each newly added counter.</li></ol><p>Next we define the ‘init’ method which constructs a default state (note that ‘init’ can also take an optional parameter in case we have a saved state)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba4b4b037bffdb15de01e1334aafccef/href">https://medium.com/media/ba4b4b037bffdb15de01e1334aafccef/href</a></iframe><p>Then we define the view function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/006a704d20dadb90b81934ee2ae24bb8/href">https://medium.com/media/006a704d20dadb90b81934ee2ae24bb8/href</a></iframe><p>The main view provides 2 buttons to trigger the ‘ADD’ and ‘RESET’ actions. The rendering of each counter is delegated to the ‘counterItemView’ function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6d5fad5ef8a8123b038c33ca99219c6/href">https://medium.com/media/b6d5fad5ef8a8123b038c33ca99219c6/href</a></iframe><p>The function adds a remove button to the item view and annotates the actions triggered by the ‘counter’ view with the id of the originating counter.</p><p>Next the update function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4cd4b4f16976950f81b5519d1669fdb/href">https://medium.com/media/f4cd4b4f16976950f81b5519d1669fdb/href</a></iframe><p>The code follows the same pattern in the previous example, children’s actions are forwarded to the originating child using the id information stored in the bubble phase. This is handled by UPDATE case which delegates to the ‘updateCounter’ function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/719adf7e066731feeb695748124e8267/href">https://medium.com/media/719adf7e066731feeb695748124e8267/href</a></iframe><p>The other actions are handled by the component itself (you can find the whole source on the GitHub repository).</p><p>The same pattern above can be applied to any tree of components and to any at degree of nesting. In spite of some overhead code that bubbles up actions and tunnels down updates, we get an uniform architecture for the whole application.</p><h4>Representing Actions with union types</h4><p>In the previous examples we used JavaScript ES6 Symbols to represent action types. And inside the views, we created objects carrying the action type as a well as additional information (id, wrapped child action).</p><p>In a real scenario w’d have to move the logic of action creation to a separate factory function (something like Action Creators in React/Flux). In the remaining of this post i’ll present an alternative that’s more in spirit of FP : <em>union types</em>. They are a subset of <a href="https://en.wikipedia.org/wiki/Algebraic_data_type">Algebraic Data Types</a> used in FP languages like Haskell, you can think of them like Enumerations but with more powerful capabilities.</p><p>Concretely, an union type will provides us with the following features at once</p><ol><li>Define a type describing all possible values of our actions</li><li>For each possible value provide us with a factory function</li><li>Provide a control flow mechanism (called pattern matching) to handle all possible variants.</li></ol><p>Unions types are not present natively in JavaScript, so w’ll use a library that emulates them. In our examples w’ll use union-type (<a href="https://github.com/paldepind/union-type">github/union-type</a>) a small and nice library written by the same author of snabbdom.</p><p>first we install the library by :</p><pre>npm install --save union-type</pre><p>Here is how we define the counter actions</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9b692906fcdb0e611f3a739400d1193/href">https://medium.com/media/b9b692906fcdb0e611f3a739400d1193/href</a></iframe><p>‘Type’ is the only function exported by the library. We use it to define our union type ‘Action’ which contains the 2 possible actions.</p><p>the returned ‘Action’ type contains factory function to create all the possible actions</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30bca1ee2947f3e663c77b7128003bfe/href">https://medium.com/media/30bca1ee2947f3e663c77b7128003bfe/href</a></iframe><p>The view creates an Increment and a Decrement action.</p><p>The update function demonstrates the use of pattern matching against different variants</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdff57640255cdda8cf77250de9484f0/href">https://medium.com/media/bdff57640255cdda8cf77250de9484f0/href</a></iframe><p>The ‘Action’ type exports a ‘case’ method which takes 2 arguments</p><ul><li>An object of the form (variant name, handler function).</li><li>the value to match against</li></ul><p>The case method then matches the provided actions against all specified cases and call the corresponding handler function. The return value is that returned by the matched handler.</p><p>Similarly, here is how ‘counterList’ actions are defined</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a44bccdd6eae7f486a514af91e6a2b4/href">https://medium.com/media/6a44bccdd6eae7f486a514af91e6a2b4/href</a></iframe><p>‘Add’ and ‘Reset’ are <em>empty actions (</em>i.e. they don’t have any field<em>)</em>, ‘Remove’ has one field (the child counter’s id). Finally the ‘Update’ action has 2 fields : the child’s id and the action triggered by that child.</p><p>We use, as usual, pattern matching in the update function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6019ca1f49e16f887026a21b5f3146d/href">https://medium.com/media/e6019ca1f49e16f887026a21b5f3146d/href</a></iframe><p>Note that the Remove and Update handlers both take parameters. If a case is matched successfully, the ‘case’ method will extract the fields from the case instance and passes them to the handler function.</p><p>So the typical pattern is :</p><ul><li>model the actions as an union type</li><li>inside the view function, create actions using the factory functions provided by the union type (Action creation can also be delegated to a separate function if the logic of creation is more complex).</li><li>inside the update function, use the ‘case’ method to match against the possible values of the union type.</li></ul><h3><strong>TodoMVC example</strong></h3><p>In this repository (<a href="https://github.com/yelouafi/snabbdom-todomvc">github/yelouafi/snabbdom-todomvc</a>)you can find an implementation of the canonical todoMVC application using the concepts in this lesson. The application consists of 2 modules :</p><ul><li>‘task.js’ which define a component that renders a single task as well as updating its state</li><li>‘todos.js’ which manages the task list as well as filtering and updating.</li></ul><p>The filtering is implemented using a trivial router based on ‘hashchange’ events. To trap window events into the main UI cycle the example use the <a href="https://github.com/paldepind/snabbdom#hooks">hook feature</a> of snabbdom (embedded as a Snabbdom extension, see ‘<a href="https://github.com/yelouafi/snabbdom-todomvc/blob/master/app/js/snabbdom-modules/window-events.js">app/js/snabbdom-modules/window-events.js</a><strong>’</strong>).</p><h3>Conclusion</h3><p>W’ve seen how to write a virtual DOM based applications using a small and standalone library. This can be helpful when we don’t want to be forced into the choices made by the React framework (esp. classes) or when we need a small sized JavaScript library.</p><p>The <em>Elm architecture</em> provides a simple pattern to write complex virtual DOM applications with all the benefits of pure functions. This gives a simple and regular structure to our code. Using regular patterns makes the application easier to maintain especially in teams with members changing frequently. A new member can quickly grasp the overall architecture of the code.</p><p>Being also implemented exclusively with pure functions, w’re sure that changing a component won’t cause undesirable side effects as long as the component code respects its contract.</p><p><em>EDITS :</em></p><ul><li><em>31–07–2015 : Added an explicit ‘init’ function in place of the ‘INIT’ action (as in the Elm tutorial)</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53b672cb2fe3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Futures & Monoids]]></title>
            <link>https://medium.com/@yelouafi/futures-and-monoids-7e9f4574bd88?source=rss-b6f1fc99587d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e9f4574bd88</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Yassine Elouafi]]></dc:creator>
            <pubDate>Tue, 21 Jul 2015 16:18:54 GMT</pubDate>
            <atom:updated>2019-02-19T12:24:05.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1y0LlZv6H95MMt60JLILtw.png" /></figure><p>In the post <a href="https://medium.com/@yelouafi/from-callback-to-future-functor-monad-6c86d9c16cb5">From Callback to Future -&gt; Functor -&gt; Monad</a> we clearly saw how Futures/Promises map to some well known constructs from FP and category theory.</p><p>First we saw that Futures are <em>Functors</em>, because they are able to take a function and apply it to their eventual outcome. Next we saw that they are also <em>Monads</em> because they are able to describe a computation as a sequence of steps through mapping a Monadic function (i.e. a function that returns itself a Monad (=Future)) then <em>flattening</em> the result to get the final result.</p><p>In this post w’ll meet another less famous construct from category theory. We will see what it represents and how it can be useful.</p><h3>Another view of Parallelism</h3><p>Remember the following use case from the first Post ?</p><blockquote>suppose we are trying to fetch some content from some web URL that can be sometimes unavailable, upon a failure of our request, we’ll try an alternative URL, we can use ‘flatMapError’ to catch the first failure and return the alternative request</blockquote><blockquote>resultF = requestF(&#39;/url1&#39;).flatMapError( err =&gt; requestF(&#39;/url2&#39;) )</blockquote><p>First we request the ‘main’ server and, upon failure, we request the alternative one. The example above can be rewritten with Promises</p><pre>resultP = requestP(‘/url1’).catch( err =&gt; requestP(‘/url2’) )</pre><p>Both examples illustrate well the sequential nature of Monads. Things has to be done one after one. But you may notice that there is a better way to solve the above use case. We don’t have to wait for the first request to fail in order to try the alternative url, we can send the 2 requests in <em>parallel</em> and just pick the first incoming response, the faster wins.</p><p>But how do we express this parallelism in Futures? we already saw that lifted functions which take multiple arguments can be used to describe parallel operations. But clearly this is not the kind of parallelism we want, so what’s the other kind ?</p><h4>Lifting revisited</h4><p>let’s quickly review the concept of <em>lifting</em>. We saw that the ‘lift’ function</p><ol><li>takes a function that operates on non future values and</li><li>returns another function that applies the same transformation to future values.</li></ol><pre>// String -&gt; Number (non lifted version)<br>function length(str) { <br>  return str.length;<br>}</pre><pre>//Future String -&gt; Future Number (lifted version)<br>lengthF = lift(length)</pre><p>We also saw that a lifted function that takes multiple Futures has to wait for <em>all of them</em> to complete before applying the underlying function.</p><p>Suppose now we want to lift the following function</p><pre>// [a] -&gt; [a]<br>function multi_id(...args) {<br>  return args;<br>}</pre><p>the function acts like an identity function but with multiple arguments, the return value is as an array of the passed inputs. Lifted to Futures, it’ll return a Future holding a list of all completion values from the input Futures.</p><pre>[Future a] -&gt; Future [a]<br>multi_idF = lift(multi_id)</pre><p>For promises, the lifted multi-id function is called ‘<a href="https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise/all">Promise.all</a>(iterable)’ which “<em>returns a promise that resolves when all of the promises in the passed in ‘iterable’ argument have resolved</em>”. As you can see, ‘Promise.all’ is just the special case of lifting the multi-Identity function.</p><p>Now, let’s imagine the above function in terms of the logical ‘and’ (‘&amp;&amp;’) operator, in a sens that the ‘completed’ property of the output future is a logical and (‘&amp;&amp;’) applied to the ‘completed’ property of all given futures</p><pre>all(fut0, fut1, ..., futN) = fut0 &amp;&amp; fut1 &amp;&amp; ... &amp;&amp; futN</pre><p>Viewed from this perspective, what’s the meaning of the logical ‘or’ (‘||’) operation applied on futures?</p><p>In an ‘and’ operation, we examine all the terms of the expression so the evaluation wont stop until the last term. Similarly in futures, the evaluation wait for the last completed future and returns all the futures.</p><p>Let’s transpose the same reasoning to ‘or’. In an ‘or’ operation, we stop the evaluation when we encounter the <em>first </em>‘true’ term. So similarly for futures, an ‘or’ operation stops on the first completed future.</p><p>Below how we may implement this operation for 2 futures</p><pre>Future.prototype.or = function(fut2) { <br>  const resultF = new Future();<br>  this.ready(tryComplete); <br>  fut2.ready(tryComplete);<br>  return resultF;</pre><pre>  function tryComplete(fut) {<br>    if(!resultF.completed) <br>      resultF.complete(val);<br>  }<br>}</pre><p>As we are only interested in the winner future, we only complete the future if it has not been already completed.</p><p>Back to our previous example, we can now express our parallelism</p><pre>resultF = requestF(‘/url1’).or( _ =&gt; requestF(‘/url2’) )</pre><p>We can easily extend the ‘or’ function to multiples arguments using the ‘forEach’ method. In this case, w’ll be defining (something similar) another operation that also exists in promises, ‘<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race">Promise.race(iterable)</a>’ which “<em>returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects</em>”.</p><blockquote>Actually this a not quite the same, <strong>Promise.race will return as soon as a promise in the iterable rejects while in our example we have to wait for the **latest promise that resolves successfully**</strong>.</blockquote><h3>Category Theory, again</h3><p>I’ll now introduce our 3rd guest from the Category theory land. Besides been a Functor and a Monad, a Future is also a <strong>Monoid.</strong></p><p>The most intuitive (although restrictive) way of thinking of Monoids is that they are <em>additives</em>. Take the analogy with the ‘or’ operation, you can start with an expression ‘a or b’, the terms of expressions are booleans, and so the result. Add another term to the expression ‘a or b or c’, the result is still a boolean. Repeat the process above with numbers and you’ll get the same result. Monoids are just simple as that (yet a very useful abstraction).</p><p>The fact that the ‘or’ operation on booleans returns always a boolean (just as the ‘+’ operation on numbers always returns a number) leads us to refine the definition : <em>Monoids needs an *additive* operation that doesn’t fall outside; </em>take for example the ‘+’ operator applied only to the range [1..12]. The range [1..12] along with the ‘+’ operation is not a Monoid because ‘11+10’ is not contained within the range. But the same range with the operation ‘(x+y) modulo 12’ (more accurately 13) forms a Monoid because whenever we <em>jump </em>by the given operation we don’t fall outside the range. This property is called <em>closure</em>. Of course Futures under the ‘race’/’or’ operation verify this as the result is always a Future.</p><p>A Monoid need also something else, called the <em>identity element</em>. Which is a value that is always <em>neutral </em>with respect to the <em>additive</em> operation. For the example of numbers under the ‘+’ operation, the identity element is zero ‘0’. With respect to the multiplication ‘x’ it is ‘1’. In the case of booleans under the ‘or’ operation it is the ‘false’ constant because ‘false or x’ will always yield ‘x’.</p><p>So what’s the identity element for Futures? The element has to be neutral with respect to the ‘or’/’race’ operation, i.e.</p><pre>future.or(identF) == identF.or(future) == future</pre><p>We need a future with the latest time of completion we can imagine, i.e. where ‘completion time == Infinity’. In other words, the identity element for Futures is <em>the never ending future</em>.</p><pre>Future.never = new Future();</pre><h4>Additive yes, but in what order?</h4><p>In fact, we have to add another requirement, the additive operation has to be <em>associative. </em>Meaning “<em>the order in which the operations are performed does not matter as long as the sequence of the operands is not changed</em>”(<a href="https://en.wikipedia.org/wiki/Associative_property">1</a>). I m pretty sure you’ve already encountred associativity in your Math School,</p><pre>a + (b + c) = (a + b) + c</pre><p>For Futures it means</p><pre>fut1 or (fut2 or fut3) = (fut1 or fut2) or fut3</pre><p>It’s not difficult to verify that the above property holds for futures. If you want to go for a formal proof, you can use a pair ‘(value, time)’ to denote the meaning of futures; and define the ‘or’ operation as</p><pre>(v1, t1) or (v2, t2) = (vk, tk) such as tk = min(t1, t2)</pre><p>I will not list the detailed proof here (I’m not that strong on Math :) ). Just note that the associativity of futures under ‘or’ results from the associativity of numbers under the ‘min’ operation</p><pre>min(t1, min(t2, t3)) == min(min(t1, t2), t3)</pre><p>In terms of promises, it means the 3 expressions below are equivalent</p><pre>Promise.race([p1, p2, p3])<br>Promise.race([p1, Promise.race([p2, p3]))<br>Promise.race([Promise.race([p1, p2]), p3]))</pre><p>So to resume, a Monoid can be described with a pair (M, op) with the following properties.</p><ul><li>x ‘op’ y = z with the requirement that x, y, z are members of M (op is known as ‘append’ or ‘mappend’)</li><li>Existence of an <strong>identity element</strong> ‘id’ such as ‘x op id = id op x = x’ for all x in M (sometimes called also ‘empty’ or ‘mempty’)</li><li><strong>Associativity</strong>. (x op y) op z = x op (y op z) for all x, y, z in M</li></ul><h3>Monoidal reduction</h3><p>You should be already familiar with the ‘<a href="https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/reduce">Array.reduce</a>’ operation. The function reduces (or folds) an array into a single value, by successively applying a binary operation to all the elements of the array. Here is the well known example of summing numbers in an array using ‘0’ as a seed.</p><pre>function sum(array) { <br>  return array.reduce( (acc, n) =&gt; acc + n, 0)<br>}</pre><p>we know that numbers form a Monoid under the ‘+’ operation. Doesn’t this give you some ideas?</p><p>If we abstract away the specific ‘number’ and ‘+’ and replace them with the more generic ‘Monoid’ and ‘append’ (additive operation) then we can normalize the ‘reduce’ operation to be working with any Monoid instance.</p><pre>function sumM(array) {<br>  return array.reduce( (acc, m) =&gt; acc.append(m), identity)<br>}</pre><p>Since Futures are Monoids themselves we can write the multi-argument Promise.race in terms of monoidal reduction</p><pre>Future.or = function(…args) {<br>  return args.reduce( (acc, fut) =&gt; acc.or(fut), Future.never )<br>}</pre><p>The ‘array.reduce’ method expects only a binary operation and optionally a seed value. But with Monoids we have additional information, we know that the binary operation is associative and that the identity element is neutral in respect to that operation.</p><p>The advantage of using Monoids is a more generic and predictable code. Using an explicit interface along with well defined properties conveys better meaning to the code, make the code more flexible and maintenable.</p><h3>Uses of Monoids</h3><h4>Example: the Writer Monad</h4><p>A typical example of Monoids is often illustrated with the <strong>Writer</strong> <strong>Monad</strong>. As for other Monads, it’s best understood through a use case : Suppose we have defined a <em>pipeline </em>of transformations by sequencing a set of functions, for example</p><pre>function increment(num) { return num + 1;   }<br>function square   (num) { return num * num; }<br>function modulo10 (num) { return num % 10;  }</pre><pre>result = modulo10( square( increment(...) ) )</pre><p>Now in order to see what’s going on inside this pipeline, we can run the example through a debugger, but sometimes this is not possible. In this case the usual solution is to log messages into the console or any other output.</p><p>The Writer Monad solves the problem by embedding the log messages directly into the intermediate and the final results. In the above example the type of the of the manipulated value is a Number. the Writer Monad will wrap the number value, say, into a pair (String, Number) where String is the type of the log messages and Number is the <em>domain</em> type manipulated by the functions.</p><pre>function WriterStr(log, val) {<br>  this.log = log;<br>  this.val = val;<br>}</pre><pre>WriterStr.prototype.bind = function (fn) {<br>  var w = fn(this.val);<br>  return new WriterStr(this.log + ‘\n’ + w.log, w.val);<br>}</pre><pre>WriterStr.unit(val) {<br>  return new WriterStr(“”, val);<br>}</pre><p>WriterStr requires the 2 operations requierd in Monads</p><ul><li>‘unit’: simply wraps the value by adding an empty log message</li><li>‘bind’ : chains the successive computations by accumulating the log messages from each step into the running log.</li></ul><p>In order to integrate our previous pipeline we have to change the normal functions into monadic ones. i.e. make them returning WriterStr instances instead of plain numbers</p><pre>function increment(num) { <br> return new WriterStr(“adding 1 to “ + num, num + 1); <br>}</pre><pre>function square(num) { <br> return new WriterStr(“squaring “ + num, num * num); <br>}</pre><pre>function modulo10(num) {<br> return new WriterStr(“applying modulo 10 to “ + num, num % 10); <br>}</pre><pre>var result = increment(5).bind( val =&gt; <br>               square(val).bind( val =&gt; <br>                 modulo10(val)))</pre><pre>//result: <br>{<br>  &quot;log&quot;:&quot;adding 1 to 5\nsquaring 6\napplying modulo 10 to 36&quot;,<br>  &quot;val&quot;:6<br>}</pre><p>The final result is a pair (log, val) where val is the final result of the computation while log, <em>its side effect</em>, is a description of all steps involved in the computation.</p><p>Now note how the Writer ‘unit’ lifts a normal value by joining an empty string to it, and how ‘bind’ applies the string concatenation on each step. As you may have already noted, String with the concatenation operation is a Monoid where the identity element is the empty string.</p><pre>String.prototype.append = String.prototype.concat<br>String.identity = &quot;&quot;</pre><p>So the Writer Monad can in fact work with any Monoid not just strings</p><pre>function Writer(append, identity) {<br>  function W(log, val) {<br>    this.log = log;<br>    this.val = val;<br>  }<br> <br>  W.unit = function(val) {<br>    return new W(identity, val);<br>  }<br> <br>  W.prototype.bind = function(fn) {<br>    var w = fn(this.val);<br>    return new W(append.call(this.log, w.log), w.val);<br>  }<br> <br>  return W;<br>}</pre><pre>var WriterList = Writer(Array.prototype.concat, []);</pre><p>and now the monadic functions has to return log messages as arrays to match the expected type for WriterList</p><pre>function increment(num) { <br>  return new WriterList([“adding 1 to “+num], num + 1); <br>}<br>...</pre><h4>Other examples</h4><p><a href="http://apfelmus.nfshost.com/articles/monoid-fingertree.html">This link</a> gives an interesting use of Monoids: exploit the generality of the Monoid interface and <a href="http://staff.city.ac.uk/~ross/papers/FingerTree.html">2–3 finger trees</a> to define a general purpose tree structure. The tree can then be reused to implement multiples data structures (lists, priority queues) by just modifying the underlying Monoid interface.</p><h3>Conclusion</h3><p>Monoids are simple structures that can be found easily everywhere : numbers, strings, lists and futures/promises are just some examples.</p><p>Their main advantage is to provide a more abstract way to factor operations that follow a pattern of <em>appending starting from an ‘empty’ element</em>. If you search through your source code there is a great chance you’ll find this pattern.</p><p>Below some links if you’re willing to learn more about Monoids (if you don’t mind reading Haskell code)</p><ul><li><a href="https://en.wikibooks.org/wiki/Haskell/Monoids">Monoid chapter from Haskell wikibook</a></li><li><a href="http://apfelmus.nfshost.com/articles/monoid-fingertree.html">Monoids and Finger Trees</a> (example cited above)</li><li><a href="http://blog.sigfpe.com/2009/01/haskell-monoids-and-their-uses.html">sigfpe article with many examples of Monoid uses</a></li><li><a href="https://github.com/fantasyland/fantasy-land#monoid">Monoids definition in fantasy-land</a> (a specification of common Alegbraic Structures in JavaScript)</li><li><a href="https://www.youtube.com/watch?v=ZhuHCtR3xq8">Brian Beckman: Don’t fear the Monad</a>, talk about Monads that explains Monoids with an accessible language</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e9f4574bd88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Promises + FP = Beautiful Streams]]></title>
            <link>https://medium.com/@yelouafi/promises-fp-beautiful-streams-6f0235c5b179?source=rss-b6f1fc99587d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f0235c5b179</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Yassine Elouafi]]></dc:creator>
            <pubDate>Fri, 17 Jul 2015 04:10:05 GMT</pubDate>
            <atom:updated>2015-12-04T09:14:25.192Z</atom:updated>
            <content:encoded><![CDATA[<p>W’ve seen that Futures/Promises emerge as a logical meaning for asynchronous functions like in this Node example :</p><pre>fs.readFile(‘…’) // =&gt; a Future/Promise</pre><p>Similarly, we w’d like to represent the meaning of functions like this</p><pre>someEventSource.on(&#39;event&#39;, ...)  // =&gt; ?</pre><p>The second code shares the asynchronous semantics of the first, hence the use of callbacks in both cases. But instead of a single future value, we are dealing here with multiples future values, more exactly a sequence of successive future values.</p><p>In this article, we will talk about an abstraction that captures the above meaning, the famous concept of <em>Stream</em>.</p><p>Look at the <a href="http://en.wikipedia.org/wiki/Stream_%28computing%29">Wikipedia definition of streams</a></p><blockquote>a sequence of data elements made available over time</blockquote><p>A Stream can be viewed like a standard list. But like Promises/Futures, it enriches the meaning of its elements with the notion of <em>time of occurrence</em>.</p><p>Streams are becoming a central abstraction in JavaScript, especially on the server side. There are of course the <a href="https://github.com/substack/stream-handbook">builtin Node streams</a>. But recent years saw the raise of another type of streams called <em>Reactive Streams</em>, they are based on the <a href="http://en.wikipedia.org/wiki/Reactive_programming">Reactive Programming</a> paradigm and was made popular into JavaScript by libraries like <a href="https://github.com/Reactive-Extensions/RxJS">Rx.js</a> and <a href="https://baconjs.github.io/">Bacon.js</a> (not to confound with the <a href="http://www.reactive-streams.org/">Reactive Streams</a> initiative, which is another newcomer).</p><p>The basic idea is that you can represent different asynchronous data like events or HTTP responses by an unifying concept called <em>observable collections</em>. Then you can manipulate those collections by standard array operations like map, filter, reduce, forEach …etc.</p><p>This article is about an interesting experiment : we will use functional programming and algebraic data types to derive a pure functional definition of RP like streams. You’ll see that it’s quite simple to roll your own, beautiful, [Reactive] Stream implementation in a surprisingly simple and extensible way.</p><p>The key difference is that for our Streams, <strong>Promises are the unit of asynchrony</strong>. The other characteristic is that they will be much easier to implement using a pure FP style (if you are familiar with Haskell or similar, you’ll recognize it immediately).</p><blockquote><em>Note: Full sources are in </em><a href="https://github.com/yelouafi/adts"><em>this Github repo</em></a><em>.</em></blockquote><h3>On the meaning of Streams</h3><p>Ok, how can functional thinking helps us to derive a nice and clean definition of streams ?</p><p>The first thing is to come up with the <em>right representation</em> for the stream type. By right i mean the one that can describe <em>all possible variants</em> of a stream. What can be a Stream ?</p><p>To represent our concept, w’ll use Algebraic Data Types (ADT) we saw in the <a href="https://medium.com/@yelouafi/javascript-and-type-thinking-735edddc388d">previous post</a>. We need to find all the possible variants of streams that capture our intent.</p><p>Since Streams are a super concept of lists let’s examine the standard lists variants. So first</p><pre>Stream a = Empty</pre><p>Naturally a stream can be empty, meaning with no occurrences on it.</p><p>Second the standard recursive definition</p><pre>Stream a = Cons a (Stream a)</pre><p>You can think of it in this sens : at the moment we have an occurrence (head), there could be more occurrences on the future or there could be nothing more (empty), in either case the following occurrences (tail) are also a Stream.</p><pre>Stream a = Abort Object</pre><p>w’d like to consider the case when a data stream, like an incoming HTTP message, interrupts due to some error, in which case we say the stream <em>aborts</em> with a given error.</p><p>Now time for our VIP guest</p><pre>Stream a = Future (Promise (Stream a))</pre><p>Literally, a Stream can be of a type ‘Future’, the type holds a value of type ‘Promise (Stream a)’ : i.e. a Promise that will resolve eventually to a Stream.</p><p>It looks like a strange variant, how can a stream be a <em>future of itself</em> ?</p><p>Imagine the following case : w’d like to get a sequence of mouse move events until a mouse press event occurs. If the user presses the mouse immediately, no mouse moves will occur so the stream will be empty. If the user moves the mouse some time before pressing it then the stream will have some occurrences, i.e. not empty.</p><p>You may see the problem : <em>we don’t know yet</em> if the stream is empty or not until we get the first mouse move or the first mouse press. Put another way, a Stream can be a future value that will resolve to another Stream representation (possibly more concrete Empty or Cons). It happens that we already have Promises for this just purpose.</p><p>Here is our complete definition</p><pre>Stream a = Empty<br>    | Abort Object<br>    | Future (Promise (Stream a))<br>    | Cons a (Stream a)</pre><p>Our representation now complete, we implement it using the <a href="https://gist.github.com/yelouafi/c33e9b1baa9b069903bc">the adt helper</a> from the previous post</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30c79b00afa2be20c1ebc64e1f408680/href">https://medium.com/media/30c79b00afa2be20c1ebc64e1f408680/href</a></iframe><p>Before we move on how to program our Stream let’s first see some examples (all the factory functions below can be found on the <a href="https://github.com/yelouafi/adtstream">Github sources</a>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4935628e6335f01b9812167055a91bc3/href">https://medium.com/media/4935628e6335f01b9812167055a91bc3/href</a></iframe><h3>Asynchronous Recursion</h3><p>The nice thing about ADTs is that implementing functions that operates on them tends to be similar : pattern matching and recursion.Our Stream is nothing more than an old good recursive ADT. It means we can program it as we do with any other recursive data type like List.</p><p>As a first demonstration, let’s define the effectful (with side effects) ‘forEach’ method. W’d like to execute an action on all occurrences of a stream, another action when the stream aborts and finally one when the stream ends</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c716b40a7d61cb847892def54aaa2570/href">https://medium.com/media/c716b40a7d61cb847892def54aaa2570/href</a></iframe><p>The whole method is a long chained <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">ternary expression</a> that matches each possible variant on the stream type. We can write such chained code because the conditional operator (?:) is associative to the right.</p><p>The big news: all stream operations we will define in this article will be nothing more than conditional expressions (yes i’m serious, all operations). FP developers will recognize that this construct maps directly to pattern matching in FP languages.</p><p>First, let’s also define a helper debug method</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38cd16f80f72296c7d039785f2c61d6d/href">https://medium.com/media/38cd16f80f72296c7d039785f2c61d6d/href</a></iframe><p>Like arrays/lists, Stream is also a Functor, the ‘map’ operation, applied on a stream, return a stream of the successive results transformed from the successive occurrences on the input stream</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/070d8b0293d1f9381fb3f7005c5141f4/href">https://medium.com/media/070d8b0293d1f9381fb3f7005c5141f4/href</a></iframe><p>Note how in the case of a promised stream, w’re doing a sort of <em>asynchronous recursion</em> because the promise callback will execute asynchronously in a <a href="http://stackoverflow.com/questions/25915634/difference-between-microtask-and-macrotask-within-an-event-loop-context"><em>microtask queue</em></a>. It means we get the benefits of a clean and concise functional/recursive code without fear of stack overflow problems.</p><p>The error handling equivalent of map, called ‘mapError’ extends the lifetime of an aborted stream by another stream</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9405bdec11c59f4aa37e79d408e91eb4/href">https://medium.com/media/9405bdec11c59f4aa37e79d408e91eb4/href</a></iframe><h3>From Haskell to JavaScript (in no time)</h3><p>If you are a Haskeller (if you are not it’s OK, you can follow reading) then you have certainly recognized the similarities with the definitions of functions on standard lists. The nice thing above is that you can easily adapt most of the concise FP definitions to define the same functions on streams.</p><p>For example take the Haskell definition of filter which returns the list of elements that satisfy a given predicate (if you don’t know Haskell JavaScript code will follow immediately)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b172b551b4b1aae148cf8c3bbb631691/href">https://medium.com/media/b172b551b4b1aae148cf8c3bbb631691/href</a></iframe><p>And here is the equivalent definition on Streams: instead of filtering elements of a list, we filter incoming occurrences as they happen</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb119e476d2d4b7fbf7cd9fb452e89f3/href">https://medium.com/media/eb119e476d2d4b7fbf7cd9fb452e89f3/href</a></iframe><p>The only difference is the Abort and Future case, which are trivially defined.</p><p>A little bit more elaborated example is the ‘span’ function which takes 2 inputs: a predicate and a list, and returns a tuple of :</p><p>1- first elements that satisfy the predicate and<br>2- the remainder of the list</p><p>Haskell code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/850400212d610ac23351e25f8eb96494/href">https://medium.com/media/850400212d610ac23351e25f8eb96494/href</a></iframe><p>Applied to streams, the function return a <em>pair</em> of streams: the first yields the first occurrences that satisfies the predicate and the second yields the remainder of the stream. The JavaScript code is derived straight from the Haskell equivalent</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e69e0c7fd97692b2d9c5ee86a8d62da/href">https://medium.com/media/3e69e0c7fd97692b2d9c5ee86a8d62da/href</a></iframe><p>Taking a more elaborated example, the ‘groupBy’ function, which groups occurrences into nested sublists/substreams given a predicate, is defined in terms of span</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fb395aaf4460dbc6c145398c9dfcf29/href">https://medium.com/media/2fb395aaf4460dbc6c145398c9dfcf29/href</a></iframe><p>Then the equality grouping function is trivially derived</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f7016ca1b7e3dc9e09421ed212d9459/href">https://medium.com/media/2f7016ca1b7e3dc9e09421ed212d9459/href</a></iframe><p>Using the same declarative approach, we can define all imaginable list operations on streams. If you know the Haskell definition (or any equivalent FP definition), then you know the Stream definition. No hard to follow async code, no event listeners, no error prone async state manipulation just pure FP code and promises.</p><p>Here are some other functions that are defined in the source code. You may try to define them by youreself before looking at the <a href="https://github.com/yelouafi/ADTStreams/blob/master/src/stream.js">Sources</a>, just think about the meaning of the resulting streamsfor each case and the answer comes quite naturally</p><ul><li>take(n) takes the first n occurrences from the stream</li><li>skip(n) skips the first n occurrences on the stream</li><li>takeWhile(predicate) takes the longest <em>prefix</em> that satisfy the predicate.</li><li>skipWhile(predicate) returns the <em>suffix</em> remaining after takeWhile</li><li>break(predicate) like span but the first stream is the longest prefix of occurrences that do not satisfy predicate</li></ul><h3>Streams and Promises interplay</h3><p>Our <em>ADT Streams</em> play nicely with Promises in various ways. In this section w’ll see some useful operations that combine the 2 concepts.</p><h4>1- Streams reduce to Promises</h4><p>As a first example, let’s take the well known ‘<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce">reduce</a>’ method (known as ‘foldl ’in Haskell). When applied to arrays, the method yields a single value representing the result of the accumulation, like the sum of an array of numbers:</p><pre>[1,2,3].reduce( (prev, cur) =&gt; prev + cur ) // =&gt; 6</pre><p>Now applied to streams (for example the sum of a stream of numbers), the final result is a future value because w’d have to wait for all future occurrences on the stream. So, the meaning of ‘Stream.reduce(…)’ is effectively a promise that will resolve to the final result of the accumulation or will be rejected in case of the stream aborted.</p><p>I find this meaning more logical than the one found in libraries like Rx or Bacon where the result of the accumulation is a <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/reduce.md">single occurrence stream</a>. It feels to me as if normal functions returned a single element array [x] instead of simply returning x itself. As a rule of thumb, we can say that <em>Streams reduce to Promises</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2888869b6fb9ef465ff9ac0cb9b72ba/href">https://medium.com/media/c2888869b6fb9ef465ff9ac0cb9b72ba/href</a></iframe><p>Higher abstract operations can be defined on top of ‘reduce’.</p><p>‘length’ which yields the number of occurrences in a stream</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52319682d48f16b78ebeb067be326f24/href">https://medium.com/media/52319682d48f16b78ebeb067be326f24/href</a></iframe><p>‘all’ Checks if all occurrences satisfy a predicate</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4acdb1e2d553a8c1afa2cef80717d8da/href">https://medium.com/media/4acdb1e2d553a8c1afa2cef80717d8da/href</a></iframe><h4>2- Streams reduce as soon as possible</h4><p>We may be tempted, as we did for ‘all’, to define the peer function ‘any’ — which yields true if any occurrence satisfies the predicate — in terms of reduce like this</p><pre>this.reduce( (prev, cur) =&gt; prev || !!pred(cur), false )</pre><p>While the above code will yield the correct value. We must be aware of the meaning of time, because ‘reduce’ will wait for all occurrences on the stream before completing the promise. But we know that the result of an ‘or’ operation can be deduced as soon as we get a ‘true’ operand</p><pre>false || /* stop here */true || false || true</pre><p>Similarly on streams, we must yield a result on the first occurrence that satisfy the predicate</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8df390b64fc3fe801ae46f0f3a656177/href">https://medium.com/media/8df390b64fc3fe801ae46f0f3a656177/href</a></iframe><p>Hence the 2nd rule of thumb : <em>Streams reduce as soon as possible</em>.</p><h4>3- *Until</h4><p>A key interplay between Streams and Promises is the <em>*until</em> operators which act on a Stream based on the completion time of a Promise.</p><p>For example, the ‘takeUntil(promise)’ will take occurrences on the stream until a given promise is resolved, or will abort the result stream if the promise is rejected.</p><p>Here is our first attempt</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c04659846657f73b094eadeb312ddeb1/href">https://medium.com/media/c04659846657f73b094eadeb312ddeb1/href</a></iframe><p>Let’s review the code, the first variant is trivial. For the 2nd variant, if the stream has already a head then yield the head and forward the <em>until</em> request to the tail (this way we yield all <em>past </em>occurrences).</p><p>The third variant deserves some discussion: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race">Promise.race(arr)</a> will return a promise that will complete as soon as one of the input promises complete, so if the ‘untilP’ promise completes first we stop taking by yielding an empty stream, and if the future stream complete first we continue taking.</p><p>There is a subtle performance problem above, if ‘Promise.race’ completes with an empty Stream (‘untilP’ wins), the second promise ‘this.promise.then( s =&gt; s.takeUntil(promise), …)’ is still active. ‘Promise.race’ just returns the winner promise, it does not stop the other competing promises from continuing (Promise cancellation is an under-discussion topic and no standard way has emerged yet).</p><p>If we can’t cancel the fulfillment of the future stream itself, we can at least stop the fulfillment propagation and thus prevent the wasetful execution of the chained blocks (like ‘s =&gt; s.takeUntil(promise)’ above). And w’d like to keep our pure FP approach so w’ll have to avoid any state manipulation.</p><p>A simple and still pure FP solution is <em>lazy evaluation</em>, instead of the competing promises resolving themselves to the desired value, w’ll make them resolve to a <em>lazy value</em> and delay the evaluation until we get the winning promise. So the code will have something like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db68c806ae65f1664c30e0e3aad20c02/href">https://medium.com/media/db68c806ae65f1664c30e0e3aad20c02/href</a></iframe><p>You can convert a promise callback returning a normal value to another returning a lazy one by simply inserting an ‘() =&gt;’ in front of the callback body, so a callback with the form ‘x =&gt; y’ will become ‘x =&gt; () =&gt; y’.</p><p>So now if the ‘untilP’ promise resolves first, no further execution will happen on the loser’s chained blocks because evaluation will be postponed until we know which way to go.</p><blockquote>Similarly to takeUnil, can you derive skipUntil which skips occurrences until a promise complete?</blockquote><h4>4- Asynchronous mapping (and filtering, taking…)</h4><p>Previously, we have defined the ‘map’ operation as taking a function of type ‘a -&gt; b’ which results on a ‘Stream b’ whose occurrences are values transformed from the input ‘Stream a’. The direct consequence of the type signature ‘a -&gt; b’ is that the resulting occurrences will happen <em>as soon</em> as the sources occurrences occur. Put another way, w’are only acting on the <em>value meaning</em> of occurrences not their <em>time meaning.</em></p><p>What if the mapping function can’t return a value immediately ? Imagine for example that we have a stream of button clicks that is mapped to a stream of ajax requests.</p><pre>// result : Stream (Promise aResponseType)<br>result = Stream.fromDomEvent(fetchButton, &#39;click&#39;)<br>               .map( e =&gt; $.ajax(...) )</pre><p>The logical meaning of the above code is that we want to map button clicks to the future responses from the ‘$.ajax(…)’ calls and not to the ajax promises themselves.</p><p>We can define a an asynchronous version of ‘map’ — something like ‘asyncMap’ — to handle this case. Another solution is to extend the <em>codomain</em> (i.e. the range of the permissible outputs) of the mapping function to accept promises beside normal values, so the type signature will pass from ‘a -&gt; b’ to ‘a -&gt; b | Promise b’ so the mapping can now return either present or future values. This way, we can have a single function that handles both the sync and async cases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72cb0fb3f250091e53bd09163339a95b/href">https://medium.com/media/72cb0fb3f250091e53bd09163339a95b/href</a></iframe><p>the trick is in ‘Promise.resolve( f(this.head) )’. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve">Promise.resolve()</a> can take both a normal value as well as another promise. In which case it’ll <em>follow</em> the passed in promise and wait for its completion.</p><p>The above reasoning is not restricted to ‘map’, it can be extended to any stream function that takes a callback (like filter, span, takeWhile, …etc).</p><p>Taking the filter example, we can make the predicate asynchronous, thus extending the range of its use cases (if the filtering decision depends for example on some asynchronous IO operation)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1dc81530e98ae74ca03a4f8f32150a8/href">https://medium.com/media/e1dc81530e98ae74ca03a4f8f32150a8/href</a></iframe><p>As said above, the same pattern can be extended to all other stream operations, opening the door to a full range of new use cases. And all this without any state manipulation neither any buffering mechanism. Just simple conditional expressions.</p><h3>Combining multiples Streams</h3><p>In imperative code, defining operations on multiples streams is a non trivial task. Because elements on different streams can occur in different moments and at different rates, we have to solve synchronization problems between different sources (ever tried to drive a state machine whose transitions depend on multiple time-separated inputs?).</p><p>In the case of <em>ADT Streams</em> the only additional complication you get is that you’ll have to pattern-match against combined cases. Usually, combined operations involves 2 streams which lead to pattern matching -at most-on 4 x 4 cases, but, as w’ll see, most cases reduce to the same answer and you’ll get generally less variants to check.</p><p>Take for example the ‘concat’ operation, which like in arrays, joins 2 streams in a sequential manner : it means the concatenation will first yield all occurrences of the first stream then passes to the 2nd.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c5f2e390ce99d39078c51aeb4af73ce/href">https://medium.com/media/6c5f2e390ce99d39078c51aeb4af73ce/href</a></iframe><p>Because all decisions depend only on the first stream, we don’t have to pattern-match on all the possible combinations but just on the first one. So the 4x4 cases reduces only to 4 cases.</p><p>Note the concatenation of 2 streams delays the occurrences from the second stream even if they occur before or interleaved withe the first one. It’s as if they were <em>buffered</em> and released after the end of the first stream. Even worse, they will never occur if the first stream is aborted.</p><p>If we want to suppress the delay effect and yields occurrences from both streams at their time, then what we need is a ‘merge’ operation that takes into account the position in time of each occurrence</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcb900796dc00a591deaa2f87d03ba5a/href">https://medium.com/media/bcb900796dc00a591deaa2f87d03ba5a/href</a></iframe><p>On merging 2 streams, <em>past values</em> (‘Cons’ case) always takes precedence (with a bias toward the 1st stream). But if the 2 streams are both promises we run a race between the two and the winner will take precedence. As with the *until functions, we use lazy values to prevent unnecessary and wasteful merging on the loser promise.</p><p>Another famous multi-list operation is ‘zip’, which pairs elements from 2 lists based on their positions ([1,2,3] zip [‘a’, ‘b’] =&gt; [ [1, ‘a’], [2, ‘b’] ]). On streams, it means each occurrence on the 2 input streams has to wait for its peer to happen before yielding the while pair :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab59a88777f817ceeed6b21fcd46f866/href">https://medium.com/media/ab59a88777f817ceeed6b21fcd46f866/href</a></iframe><h3>Monadic Streams</h3><p>Until now we have considered occurrences of a Stream as normal JavaScript values. What if the incoming occurrences are Streams by themselves ? i.e. what is the meaning of a Stream of Streams? or put another way: How do we <em>flatten</em> a 2-layered stream ?</p><p>There is no single answer to the above question as we can combine nested streams in different ways.</p><p>We can merge the nested streams: we yield occurrences from the 1st incoming stream (that comes with the 1st occurrence), then when the 2nd stream appears we merge it with 1st stream and so on. For example, imagine we have a chat room with new users coming over time, and each user can type multiple messages in the chat room. The chat room can be viewed as a stream of incoming users, and each incoming user himself can be viewed as a stream of incoming messages, so we end up with a stream whose occurrences (users) are themselves streams(messages from each user). The log of all messages from all users, present and futures, is the merge of messages from all users.</p><p>Another way to flatten a 2-layered Stream is to concatenate the nested streams side by side, i.e. we take all occurrences from the 1st incoming stream, then we take the occurrences from the 2nd incoming stream …etc. As a practical example, imagine now we’re sending an ajax request each time the user hits a button, and suppose we can get, for each request, a stream representing the response body, so we end up with a stream whose occurrences (ajax responses) are themselves streams (body of each response). The log of all bodies, printed one after another, is the concatenation of bodies from all ajax responses.</p><p>In fact, if you think a little about it, flattening a stream is quite similar to the ‘reduce’ operation, we combine nested occurrences by a binary function as they appear on the stream. So we can define a generic flattening version</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29cdca954a06ba5c25636e5f496367e6/href">https://medium.com/media/29cdca954a06ba5c25636e5f496367e6/href</a></iframe><p>Then we can define specialized versions in terms of the generic flatten. For example the <em>flatten-by-merge</em> operation can be defined like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/017a3ef10452d52abb6186ac0fb11da0/href">https://medium.com/media/017a3ef10452d52abb6186ac0fb11da0/href</a></iframe><p>Similarly, the <em>flatten-by-concat</em> is</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b91904fb72f6a705ec7ee4a3d332248/href">https://medium.com/media/7b91904fb72f6a705ec7ee4a3d332248/href</a></iframe><p>And so you can easily flatten by any binary operation.</p><p>The meaning of the monadic operation ‘flatMap’ (or bind, or chain) is less obvious : mapping a stream with a function that transforms each occurrence on the source stream into a child stream, then flatten all generated streams.</p><p>For example, the meaning of ‘mergeMap’ is mapping with a function that transforms occurrences into sub-streams then merge all generated streams</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03ab7ee44de3b546632cdde0d2a9824a/href">https://medium.com/media/03ab7ee44de3b546632cdde0d2a9824a/href</a></iframe><p>Similarly, ‘concatMap’ concatenates generated sub-streams</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56802a541a81e3ce057181e2437dc4d4/href">https://medium.com/media/56802a541a81e3ce057181e2437dc4d4/href</a></iframe><h3>Throttling and Debouncing</h3><p>I did not want to conclude before testing how ADT streams can handle some advanced operations found on RP Stream libraries, i’ll take the famous examples of <em>throttling</em> and <em>debouncing</em>.</p><p>You may be aware of the terms from libraries like JQuery or Underscore. There are also present with multiple variants on most RP libraries.</p><p>The simplest of both is <em>throttling</em>; a simple illustration is when handling mouse move events, instead of running the handler on each mouse event, you may prefer to <em>skip</em> some move events for performance reason. For example you may choose to handle a single mouse move event once each 50 milliseconds.</p><p>If you look to a conventional/imperative implementation of throttling (for example form <a href="http://underscorejs.org/docs/underscore.html">Underscore sources</a>), you’ll see a bunch of state variables and timeouts operations along with the required synchronization code. As i intend to keep my promise on the beginning of this article, the actual Stream definition will be no more than a single conditional expression</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a15281c460dafea313f2abc9606d5dd/href">https://medium.com/media/0a15281c460dafea313f2abc9606d5dd/href</a></iframe><p>Let’s review the code, throttle takes a <em>generator</em> function ‘() =&gt; Promise’, w’ll use it to generate a new event whenever we start a new throttling iteration. This way we can throttle by any event not just timeouts.</p><p>As soon as we get an input, we yield it then skip all subsequent inputs until the throttling event terminates (‘skipUntil’ will skip occurrences from the tail until the passed in promise completes).</p><p>The case of debouncing is a little bit complicated. Basically, debouncing is a technique that can be used to optimize handling of events that occurs at a rapid rate.</p><p>For example, if you’re handling the window ‘resize’ event in the browser, you’ll get all ‘resize’ events as the user keeps dragging the mouse. If you’re doing some heavy DOM manipulations inside your handler you may prefer to let the user finish resizing and react directly to the final result (window size). We can suppose that if a period of 500ms passed without receiving any resize event, then the user may have finished dragging and then we handle the last event occurred before this <em>quiet</em> period. We say that w’ve debounced the resize event by a delay of 500ms.</p><p>Implementing debouncing can be a bit tricky using imperative stateful code, w’ve get to run timeouts on each event occurrence and do some state housekeeping in order to keep track of the delay between successive occurrences.</p><p>As usual, in our ADT streams, this is just another conditional expression</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2edd1d468f4d78cea96ed2b9f85b232d/href">https://medium.com/media/2edd1d468f4d78cea96ed2b9f85b232d/href</a></iframe><p>‘debounce’ takes also a generator function to make new debouncing events. We use an accumulating input ‘last’ to mark if w’re inside an ongoing debounce operation (ie w’ve a last input to be checked). The ‘undef’ special value let us know if there were any precedent input (we can’t use null or undefined because streams can yield any JavaScript value).</p><p>As soon as w’ve got an input (the Cons case) we start debouncing using its value. And if the tail is a future, we run a race between a new generated event (call to ‘event()’ inside Promise.race) and the tail itself, if the debouncing event wins, it means no occurrences happened in the stream during this period so we include the last input and start a new debouncing iteration. if instead, the future tail wins, then there were occurrence(s) before the debouncing event, so the last input is not (yet) included and we continue debouncing with the completed tail.</p><p>Note we do not discard yet the last input because w’d have to know the type of the completed tail : if it is Empty or Abort then we include the last input (because w’re sure there will be no more occurrences). If it is a Cons, then we effectively discard it and restart debouncing with the new head.</p><p>As a said, that’s a little more complicated but even, w’ve managed to do it with a simple (a little longer) conditional expression, meaning no state and no imperative code.</p><h3>Conclusion</h3><p>You can find the complete sources at <a href="https://github.com/yelouafi/ADTStreams">Github</a> along with usage instructions.</p><p>Note it’s more about experimenting a concept than releasing a new library. The main intention of the Github Sources is to provide a starting point for anyone willing to go further with this. Hopefully, there will be people providing some useful feedback on the concept and its real world feasibility. What follows are some general thoughts on the practical issues</p><h4>Testing vs proof</h4><p>I putted some unit tests in the sources (obviously this is far from enough). For a lot of reasons, it’s a not a good idea to test this kind of code in a real machine so i used the concept of a <em>Virtual Scheduler</em> borrowed from the RX library. The scheduler can generate virtual and precise timeouts events so we can test all Stream operations in a precise and deterministic environment.</p><p>But i’m still thinking that, speaking of unit tests, it’s never enough. We feed our functions with some inputs and make assertions on the output. Unit testing, while important, is just a poor, and probabilistic way of <em>proof</em>.</p><p>While we can’t go for a formal proof method, we can do better than standard unit tests: i’m thinking of something like <a href="https://www.fpcomplete.com/user/pbv/an-introduction-to-quickcheck-testing">Quickcheck</a> in Haskell, w’re still in the testing land, but now instead of testing a few inputs we test for <em>invariants</em>, i.e. general properties that our function should satisfy. This is best motivated by this quote from the above link</p><blockquote>(…) you might be able to guess some more interesting cases to check for “edge” conditions (…). But another issue is figuring out what the right answers should be for such cases. This is not too difficult for a simple function, but can be much harder for more complex problems — — even for experienced programmers.</blockquote><p>So the idea is to think of properties a function should verify for each possible input, write the property assertion and the testing framework will try to fail the assertion by checking it against a high number of generated inputs. A simple example is of the ‘reverse’ function on lists : logically, reversing an already reversed list shoud yield the original list</p><pre>reverse( reverse(list) ) == list</pre><p>Obviously this is more reliable than testing against 2 or 3 sample inputs.</p><p>I think there exist some Quickcheck based libraries in JavaScript so the idea should be feasible. The trick is — of course — to come out with pertinent assertions for each stream function.</p><h4>Resource consumption</h4><p>In reality, i’m less worried about the correctness of the definitions (they are derived from Haskell after all) than i’m about resources, time and memory.</p><p>For the time question, i think the key factor is the promise case : promises execute their then blocks asynchronously in a <a href="http://stackoverflow.com/questions/25915634/difference-between-microtask-and-macrotask-within-an-event-loop-context">microtask queue</a>, this prevents stack issues but can introduce some latency issues, especially when we’re dealing with occurrences happening at an extremely rapid rate. For most use cases, i think this is less from an issue, because in a microtask queue (a true and not a timeout emulator) w’re still far from the milliseconds magnitude but maybe i’m missing something here.</p><p>For the memory issue, ADT Streams in themselves are very lightweight objects (one or 2 variables), and the question translates directly to a more general Garbage Collector/Object retention problem. If you hold a long living reference to a huge Stream (like a global variable in the browser) then the entire Stream chain will be kept in memory. So we’ve to avoid global or other kind of long living references (like module properties).</p><p>IMO, the real cool thing about ADT Streams is that they open a full, and infinite, range of possibilities on stream programmability.</p><p>The ADT concept simplifies a lot the programming model, and the Promise variant makes handling asynchronous cases a lot more simple. Instead of providing a big monolithic library with a huge list of operations, we can instead provide just a tiny core with a small set of operations and anyone can define the needed operations using a clean and beautiful FP style.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f0235c5b179" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript and Type Thinking]]></title>
            <link>https://medium.com/@yelouafi/javascript-and-type-thinking-735edddc388d?source=rss-b6f1fc99587d------2</link>
            <guid isPermaLink="false">https://medium.com/p/735edddc388d</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algebraic-data-types]]></category>
            <dc:creator><![CDATA[Yassine Elouafi]]></dc:creator>
            <pubDate>Thu, 16 Jul 2015 15:27:40 GMT</pubDate>
            <atom:updated>2016-10-06T11:49:17.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Lvpct1eq9cjBgFWI2wJ3g.jpeg" /></figure><p>At the heart of functional thinking is to ask about the meaning of things. In the case of functions, it’s reasoning about their return values. But, that’s actually insufficient, as important as is, to give the full answer.</p><p>Basically, a function is a relation between <em>a set of </em>inputs <em>-a domain-</em> and a set of outputs<em> -a codomain-</em> (along with a fundamental constraint: the same inputs always produces the same outputs). So we have also to ask, in addition of the return value, about the permissible inputs and outputs of a function. In the world of programming, that leads us straight to reasoning about <em>types</em>.</p><p>It maybe be surprising to talk about types in a dynamic language like JavaScript, without static/explicit typing. The truth is, <strong>consciously or subconsciously, you are always reasoning with your types</strong>, JavaScript still has to check your types, although this is delayed until execution (<em>late binding</em>). And you still has to think of what operations you can invoke on this or that variable.</p><p>In this post i’ll (try to) show you that <em>type thinking</em> is more than tagging a variable with a data type to get those precious compiler messages, and more importantly, you don’t have to work with a statically typed language in order to reason about your program types (just as you don’t need to work in a purely functional language in order to do functional thinking).</p><blockquote>The post use a Haskell-like syntax to denote functions type signature :</blockquote><blockquote>=&gt; ‘f : a -&gt; b’ means f is a function that takes an argument of type a and returns a result of type b. a and b are considered generic types<br>=&gt; Multiple arguments are enclosed in parentheses : ‘f : (a, b) -&gt; b’<br>=&gt; ‘a | b’ denotes an union type either of type ‘a’ or type ‘b’.<br>=&gt; ‘Future a’ means a ‘Future’ parametrized with a generic type ‘a’</blockquote><h3>Error handling revisited</h3><p>You may recall in the <a href="https://medium.com/@yelouafi/from-callback-to-future-functor-monad-6c86d9c16cb5">post about Futures</a> how we solved the error handling problem: we introduced the concept of failure to our Future type, thus derived the new operations for error handling: ‘fmapError’ and ‘flatMapError’.</p><p>The truth is that i’m not fully convinced with the above solution (i’m pretty sure any FP guy would think the same thing).</p><p>First with more concepts comes more complication, we’d have to deal with more cases both in our semantic model and our implementation. IMO, a ‘Future’ has to deal only with one thing, describing values that will occur in the future and nothing more. Any meaning that may be given to this values must be defined in their proper computational context. <em>FP is all about expressing complex things out from composing simpler things</em> (while in contrast, imperative programming is often about expressing simple things using more complex things under the hood).</p><p>And after all, errors are not necessarily a proper concept of Futures but are relevant to any function, be it synchronous or asynchronous.</p><p>Second reason is practical, actually i’d rather classify errors into 2 kinds:</p><ol><li>Semantic errors are integral part of the problem space (like converting a string to a number that may fail if the string is not a valid numeric representation)</li><li>Runtime errors are errors that typically arise from bugs in the code (type error, undefined function name, …)</li></ol><p>Observe this code from the definition of ‘fmap’</p><pre>Future.prototype.fmap = function(fn) {<br>    // ...             <br>    try { <br>        fut.complete( fn(val) );    <br>    }<br>    catch(err) { <br>        fut.fail(err);              <br>    }                 </pre><pre>}</pre><p>The ad-hoc catch statement inside ‘fmap’ will catch both error types — semantic and bugs — and fail the future with whatever error is caught. While i find it natural to fail the Future with an expected erroneous result of a function call, i don’t think it’s same for bugs or runtime errors.</p><p>Third and more fundamentally, the solution isn’t really in the spirit of functional thinking, which is all about defining functions.</p><p>A try/catch block makes sens only if we are thinking in terms of <em>executable statements</em>, but in denotational thinking there is not such a meaning to the above code. Denotational world is made of relations between things without reference to any execution model.</p><p>So how do we deal with errors in functional terms? it’s quite simple, and you may already know it, just consider the simple code below, what’s the type of the following ‘toNumber’ function</p><pre>const toNumber = str =&gt; Number(str)</pre><p>Before you answer, consider what happens if you run this expression?</p><pre>toNumber(&quot;not a number&quot;) // =&gt; NaN</pre><p>Executing the equivalent code in a language like Java will immediately throw a ‘ NumberFormatException’ at your face but above instead it returns a curious ‘NaN’ type. Believe it or not, but the JavaScript solution is more or less similar to what we may do in a purely functional language.</p><p>In the Java case, we say that ‘toNumber’ is a <em>partial function</em>. Indeed, it can’t give an answer to all inputs. So the function just raises an exception. Put another way, the function isn’t defined over the full domain of strings but only those representing valid number representations.</p><p>What JavaScript does actually is simulating a common pattern in FP : <em>extending the codomain</em> of the function— the set of its permissible outputs — so the function can actually return either a <em>valid </em>number or the curious ‘NaN’ value.</p><p>Let’s apply the same trick to our error handling problem: If a function may return some error, we just extend it’s codomain to permit errors as return values; So we also define a new type</p><pre>Result a = Success a  | Error Object</pre><p>The meaning of above is: ‘Result’ defines, for each underlying type ‘a’, a new type that is either a ‘Success’ holding a value of the same type ‘a’ or an ‘Error’ holding an error object. Both sides of the definition are called <em>variants</em> of the Result type. Think of ‘Success’ and ‘Error’ as <em>specializations</em> of the more abstract ‘Result’ giving us more information about a given ‘Result’ value.</p><p>You can view ‘Result’ as another box type, just like ‘Array’ or ‘Future’ defined in the previous post. And by box, i mean <em>it gives a context</em> to an underlying value. If you take only a value of type ‘a’, its meaning is nothing more than that given by its type. Now, put it inside a ‘Success’ box, and the meaning is enriched, it now denotes a successful result of a computation.</p><p>This makes a subtle and important difference, you can move a ‘Result’ all around within your code without any loss of its initial context. Contrast this with inline error handling when you have to deal with the error as soon as it occurs, otherwise you lose its context (a typical problem in node async functions, where errors can get lost if you forget to handle them in place).</p><p>‘Result’ is an example of what we call <a href="http://en.wikipedia.org/wiki/Algebraic_data_type"><em>Algebraic Data Types</em></a> or just ADTs, which are basically types formed by composing other types. ‘Success’ and ‘Error’ are also called <em>constructors</em> because they give us concrete instances of the ‘Result’ type (actually they are more factory functions than traditional JavaScript constructors).</p><p>A possible implementation of ‘Result’ in JavaScript is given below:</p><pre>// private constructor<br>function Result(isError, data) {<br>    this.isError = isError;<br>    this.data = data;<br>}</pre><pre>// public factories<br>Result.Success = val =&gt; new Result(false, val);<br>Result.Error = err =&gt; new Result(true, err);</pre><p>Here is an example of usage with a Future and an async node function</p><pre>// readFileF : (String, Object) -&gt; Future (Result String)<br>function readFileF(file, options) {<br>    var f = new Future();<br>    fs.readFile(file, options, (err, data) =&gt; { <br>        const res = err ? Result.Error(err) : Result.Success(data);<br>        f.complete(res);<br>    });<br>    return f;<br>}</pre><p>Since ‘readFile’ may fail, we wrap its result in a Result type to denote its outcome (Success or Error).</p><p>In final, we obtain a value of type ‘Future (Result String)’, a Future holding the eventual Result of the file read operation.</p><p>As with Future, Result type is a Functor instance (let’s call its mapping method ‘map’ as in Arrays):</p><pre>// map : (Result a, a -&gt; b) -&gt; Result b<br>Result.prototype.map = function(f) {<br>    return this.isError ? this : Result.Success( f(this.data) );<br>}</pre><p>above, ‘map’ applies the function only to successful values and forward errors.</p><p>The peer function to handle errors do the inverse, catching and transforming errors while forwarding successful results:</p><pre>// mapError : (Result a, a -&gt; b) -&gt; Result b<br>Result.prototype.mapError = function(f) {<br>    return this.isError ? Result.Success( f(this.data) ) : this;<br>}</pre><p>Result is also a Monad, we define the sequencing operation ‘chain’ (which is more sounding than flatMap)</p><pre>// chain: (Result a, a -&gt; Result b) -&gt; Result b<br>Result.prototype.chain = function(f) {<br>    return this.isError ? this : f(this.data);<br>}</pre><p>Like ‘map’, ‘chain’ captures and transforms valid results while forwarding errors.</p><p>And the error handling equivalent which do the inverse</p><pre>// chainError : (Result a, a -&gt; Result b) -&gt; Result b<br>Result.prototype.chainError = function(f) {<br>    return this.isError ? f(this.data) : this;<br>}</pre><p>In the same spirit of the first post, we <em>lift</em> normal functions to act on values of type Result.</p><pre>// lift1 : (a -&gt; b) -&gt; (Result a -&gt; Result b)<br>Result.lift1 = f =&gt; (res =&gt; res.map(f))</pre><pre>// error equivalent<br>Result.liftError = f =&gt; ( res =&gt; res.mapError(f) )</pre><p>For lifting functions with more than 1 argument, since Result is a Monad instance, we can apply the same trick used with Future: using the sequencing operation (chain) to collect arguments, for example here is ‘lift2’ which lifts 2-ary functions</p><pre>// lift2 : ( (a, b) -&gt; c ) -&gt; ( (Result a, Result b) -&gt; Result c )<br>Result.lift2 = f =&gt; ((res1, res2) =&gt;<br>    res1.chain( v1 =&gt;<br>        res2.chain( v2 =&gt; <br>            Result.Success(v1, v2)<br>        )<br>    ))</pre><p>Or we can cheat by looking directly inside the Result box</p><pre>// lift : ( (a, b, ...) -&gt; x ) -&gt; ( (Result a, Result b, ...) -&gt; Result x ) <br>Result.lift = function(f) {<br>    return (...args) =&gt; {<br>        for(var i = 0, len = args.length; i &lt; len; i++) {<br>            var ai = args[i];<br>            if(ai.isError) return ai;<br>        }<br>        return Result.Success( f.apply(this, args) )<br>    }<br>}</pre><p>‘lift’ proceeds only if all its arguments are successful otherwise it returns the first error encountered.</p><p>Here is an example of counting the length of a file content.</p><pre>// String -&gt; Future (Result Number)<br>readFileF(&#39;test.txt&#39;).map( s =&gt; s.length );</pre><p>We can even implement the error handling operations as methods of Future</p><pre>// this : Future (Result a)<br>// f    : Result a -&gt; Result b<br>Future.prototype.fmap = function(f) {   <br>    var fut = new Future();<br>    this.ready( res =&gt; fut.complete(f(res)) );    <br>    return fut;<br>}       </pre><pre>// f : a -&gt; b<br>// mapSuccess, mapError: (Future(Result a), f) -&gt; Future(Result b)<br>Future.prototype.mapSuccess = function(f) {<br>    return this.fmap( Result.lift(f) );<br>}</pre><pre>Future.prototype.mapError = function(f) {<br>    return this.fmap( Result.liftError(f) );<br>}</pre><pre>// fut: Future (Result Number)<br>fut = readFileF(&#39;invalid path&#39;)<br>        .mapSuccess( s =&gt; s.length )<br>        .mapError( () =&gt; -1 )</pre><p>To catch errors in monadic computations</p><pre>// f : a -&gt; Future (Result b)<br>// flatMapSuccess : (Future (Result a), f) -&gt; Future (Result b)<br>Future.prototype.flatMapSuccess = function(f) {<br>    return this.flatMap( <br>      res =&gt; res.isError ? Future.unit(res) : f(res.data)<br>    )<br>};</pre><pre>Future.prototype.flatMapError = function(f) {<br>    return this.flatMap( <br>      res =&gt; res.isError ? f(res.data) : Future.unit(res)<br>    );<br>}; </pre><pre>// requestF : String -&gt; Future (Result String)<br>resultF = requestF(&#39;/url1&#39;)<br>           .flatMapError( res =&gt; requestF(&#39;/url2&#39;) )</pre><h3>Recursive ADTs</h3><p>The type definition of Result is quite simple: a disjoint union between 2 other types. But the real power of ADTs lies elsewhere.</p><p>Consider the definition below, ubiquitous in functional programming literature, and quite similar to a linked list definition as found in imperative languages</p><pre>List a = Empty | Cons a (List a)</pre><p>The above annotation can be read as:</p><ul><li>‘List’ is a type that defines, for each underlying type ‘a’, a new type which can be either:</li><li>an ‘Empty’ list, or</li><li>a ‘<a href="http://en.wikipedia.org/wiki/Cons">Cons</a>’ of 2 values :</li><li>the first, its <em>head</em>, is of the underlying type ‘a’ and the second, its ‘tail’, is another List of ‘a’.</li></ul><p>‘List’ is a typical example of a <em>recursive type</em>, i.e. a type that may be defined in terms of itself.</p><p>The form ‘List a = Empty | Cons a (List a)’ — borrowed from Haskell syntax — looks a clean and concise way to express things. Unfortunately, JavaScript doesn’t have syntax support for ADTs. We can still implement them using functions and objects, like we did early, but i propose another solution: a helper function that can make an ADT with a more concise syntax using ES6 object literals</p><pre>function List() {}<br>adt(List, {<br>  Empty : new List(), // a singleton<br>  Cons  : (head, tail) =&gt; ({head, tail}) // a factory function<br>});</pre><p>Not as concise as the Haskell definition but still better than verbose object creations (If you are interested <a href="https://gist.github.com/yelouafi/c33e9b1baa9b069903bc">here is the source code of ‘adt’</a>).</p><p>An interesting property of types like List is that implementing operations on them follows naturally their recursive nature, take a look at the below definitions of some familiar list operations:</p><p>The well known ‘map’ function to transform list elements through a mapping function ‘f’</p><pre>// map : (a -&gt; b, List a) -&gt; List b<br>function map(f, list) {         <br>  return list.isEmpty ? List.Empty<br>                      : List.Cons(f(list.head), map(f, list.tail))<br>}</pre><p>The ‘filter’ function can be defined the same way</p><pre>// aBoolean : Object (JavaScript view of truth)<br>// filter : (a -&gt; aBoolean, List a) -&gt; List a<br>function filter(f, list) {<br>  return list.isEmpty ? <br>                 List.Empty<br>               : (f(list.head) ?<br>                    List.Cons(list.head, filter(f, list.tail))<br>                  : filter(f));             <br>}</pre><p>‘take’ which takes the first ‘n’ items from the beginning of the list</p><pre>// take : (Number, List a) -&gt; List a<br>function take(n, list) {<br>        return this.isEmpty || n &lt; 1 ? <br>            List.Empty<br>          : List.Cons(list.head, take(n-1, list.tail)) <br>}</pre><p>The usage of recursion in all the definitions above is a fundamental pattern in recursive types. It is a typical case of <em>pattern matching</em> because we are matching each variant in the type in order to decide what to do.</p><h3>Infinity via Laziness</h3><p>Another useful property of recursive types is the ability to define <em>infinite data structures</em>. Consider for example this function which builds an infinite list from a single value</p><pre>// repeat : a -&gt; List a<br>repeat = val =&gt; List.Cons( val, repeat(val) )</pre><pre>// takes 5 &#39;Hi&#39;s<br>take(5, repeat(&#39;Hi&#39;))</pre><p>If you run this code in JavaScript, you’ll soon get a “Maximum call stack size exceeded” error.</p><p>This simple example illustrates the most fundamental difference between (purely) functional and imperative languages.</p><p>In order to evaluate the ‘take(5, repeat(‘Hi’))’ call, JavaScript starts from <em>inside; </em>as detailed in the sequence below</p><ol><li>evaluate take(5, repeat(‘Hi’)) leads to evaluating the 2 given arguments</li><li>evaluate the 1st argument 5</li><li>evaluate repeat(‘Hi’) which expands to List.Cons( ‘Hi’, repeat(‘Hi’) )</li><li>again evaluate the 2 arguments of List.Cons, starting with ‘Hi’</li><li>then evaluate repeat(‘Hi’) which brings us back to step 3</li></ol><p>And so on, since there is no <em>terminating condition</em> to break the recursive calls the program will, theoretically, never terminates.</p><p>In a typical FP language like Haskell the evaluation will starts from <em>outside. </em>Evaluation of ‘take(5, repeat(‘Hi’))’ will not evaluate the given arguments immediately, instead the runtime <em>expands </em>the body of ‘take’. In FP jargon, we say that expression ‘take(5, repeat(‘Hi’))’ is <em>substituted</em> with the equivalent definition.</p><p>In the example above, we can trace the evaluation by respectively subsituing terms in the experssion by their corresponding definitions. Here is an illustration of the first steps</p><pre>1 =&gt; take(5, repeat(&#39;Hi&#39;))</pre><pre>2 =&gt; *repeat(&#39;Hi&#39;)*.isEmpty || 5 &lt; 1 ? <br>            List.Empty<br>          : List.Cons(*repeat(&#39;Hi&#39;)*.head, <br>                      take(5-1, *repeat(&#39;Hi&#39;)*.tail))</pre><pre>// expands *repeat(&#39;Hi&#39;)*<br>3 =&gt; List.Cons(&#39;Hi&#39;, repeat(&#39;Hi&#39;)).isEmpty || 5 &lt; 1 ?<br>         List.Empty<br>       : List.Cons(List.Cons(&#39;Hi&#39;, repeat(&#39;Hi&#39;)).head,<br>                   take(5-1, List.Cons(&#39;Hi&#39;, repeat(&#39;Hi&#39;)).tail)) </pre><pre>4 =&gt; List.Cons(List.Cons(&#39;Hi&#39;, repeat(&#39;Hi&#39;)).head, <br>               take(5-1, List.Cons(&#39;Hi&#39;, repeat(&#39;Hi&#39;)).tail))</pre><pre>5 =&gt; List.Cons(&#39;Hi&#39;, take(4, repeat(&#39;Hi&#39;)))</pre><pre>6 =&gt; List.Cons(&#39;Hi&#39;, take(4, **same as in step 2**))</pre><p>Note how the evaluation of ‘repeat(‘Hi’)’ is delayed until the step 3, where we <em>look into</em> the list in order to decide if it’s empty or not. Also note how the expansion from the step 3 gives us only ‘List.Cons(‘Hi’, repeat(‘Hi’))’ instead of the entire list. We don’t actually need the full/infinte list in order to evaluate if the list is empty or not, the returned ‘List.Cons(‘Hi’, …)’ expression is sufficient by itself.</p><p>So completing the sequence of evaluations above will expand repeat(‘Hi’) only when necessary, as we are advancing in our process. Once we reach the step where ‘n == 0’ , the ‘take’ expression will yield the ‘List.Empty’ result so no further evaluation will take place.</p><p>We say pure FP languages are <em>lazy</em>. They defer evaluation of expressions until necessary. In the example above, the need to evaluate the second argument will not occur until the take function <em>start looking inside</em> the given list to make a decision (if empty stop taking, if not continue taking). “<em>start looking inside”</em> in FP jargon is called <em>pattern matching</em> because we are matching the List ADT with each of its variants. This is the reason we say that in FP, evaluation is essentially driven by pattern matching.</p><p>In contrast, languages like JavaScript are said to be <em>strict</em>, or with <em>eager evaluation</em> because expressions like in function arguments will be evaluated immediately.</p><p>Although JavaScript is not a lazy language, it’s easy to define infinite types by simulating laziness. Back to the List example, we modify the list definition</p><pre>List a = Empty <br>       | Cons a (List a)<br>       | Lazy () -&gt; List a</pre><p>The new definition adds a new variant, a List can now also be a ‘Lazy’ list with a <em>thunk </em>: a getter function taking no input and returning a ‘List’. This way, the thunk function can express our meaning without actually evaluating it, we’ll decide ourselves when to force its evaluation. In fact, you can use this trick to transform any expression ‘x’ by simply putting ‘() =&gt;’ in front of it(eg. ‘x+y’ will become ‘() =&gt; x+y’ and if x and y are themeslves lazy values the expression becomes ‘() =&gt; x()+y()’).</p><p>The new definition using our adt helper function is</p><pre>function List() {}<br>adt( List, {<br>  Empty : new List(),<br>  Cons  : (head, tail) =&gt; ({head, tail}),<br>  Lazy  : thunk =&gt; ({thunk})<br>})</pre><p>Now we can create an infinite list by making the 2nd argument to ‘repeat’ a lazy list</p><pre>repeat = val =&gt; List.Cons(val, List.Lazy(() =&gt; repeat(val)))</pre><p>Here is an example on how to define the ‘filter’ function given the new definition</p><pre>// filter: (a -&gt; aBoolean, List a) -&gt; List b<br>function filter(pred, list) {<br>  return list.isEmpty ? List.Empty<br>       : list.isCons  ? <br>           ( pred(list.head) ?<br>               List.Cons(list.head, filter(pred, list.tail)<br>             : filter(pred, list.tail)<br>            )<br>        /* isLazy */ List.Lazy( () =&gt; filter(pred, list.thunk())<br>}</pre><p>In the case of a lazy list, we just return another lazy list that reflects the filter on the materialized list.</p><p>The question here, when to force the evaluation of a lazy list?</p><p>We’ve seen that in FP languages, evaluation is principally driven by pattern matching, but in our precise case, that’s entirely up to us. We could implement all list functions lazily like in ‘filter’ above, but it obviously doesn’t make sense, sooner or later we’ll have to do something with the real values.</p><p>For example, we can decide to force evaluation in the ‘take’ function (making it a <em>strict</em> function in a certain term)</p><pre>// take : (Number, List a) -&gt; List a<br>function take(n, list) { <br>  return list.isEmpty || n &lt; 1 ? List.Empty <br>      :  list.isCons ? List.Cons(list.head, take(n-1, list.tail))<br>      :  /* isLazy  */ take(n, list.thunk()) // forces evaluation</pre><p>Here is an example that builds an infinite list of natural numbers, then takes the first 5 odd ones.</p><pre>// an infinite list of natural numbers<br>nats = start =&gt; List.Cons(start, List.Lazy(() =&gt; nats(start+1)))</pre><pre>// an infinite list of odd naturals<br>odds = filter(n =&gt; n%2, nats(0))</pre><pre>// 5 first odd naturals<br>fiveodds = take(5, odds) </pre><p>Recursive ADTs offers a more concise way to define operations using pattern matching and recursion, but in the cons part, if you have a big List, recursion can be a problem in the case of languages like JavaScript (<a href="http://www.2ality.com/2014/04/call-stack-size.html">here is a useful link to read more about this</a>). This is not a problem in functional languages like Haskell which handle recursive calls quite efficiently.</p><h3>Conclusion</h3><p>ADTs are muchmore than just a syntax sugar or a repackaging of the existing OOP types. They offer a conceptual basis to reason about your program entities, forcing you to think explicitly about your function’s domains and codomains.</p><p>Simple ADTs like the ‘Result’ type, can serves as a context that enriches the meaning of simple values with additional information (is this value an error or a success value ?)</p><p>Recursive ADTs can offer a powerful abstraction to model complex data structures and implement their operations in a beautiful and concise code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=735edddc388d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Callback to Future -> Functor -> Monad]]></title>
            <link>https://medium.com/hackernoon/from-callback-to-future-functor-monad-6c86d9c16cb5?source=rss-b6f1fc99587d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c86d9c16cb5</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Yassine Elouafi]]></dc:creator>
            <pubDate>Tue, 14 Jul 2015 03:20:18 GMT</pubDate>
            <atom:updated>2019-05-21T04:26:52.585Z</atom:updated>
            <content:encoded><![CDATA[<h4>Motivation</h4><p>A fundamental concept in functional programming is <strong>composition</strong>. It simply describes the mechanism by which we combine simpler things to build more complicated things, then combine the new resulting things to build higher-complicated things and so on.</p><p>With composition, you never hit a wall, because you must always ask yourself <em>“What is the return value of this function ?”</em>, or put another way <em>“What is the meaning of this thing ?”</em></p><p>If you’ve been in Node.js you are certainly aware of the code below</p><pre>fs.readFile(&#39;...&#39;, function (err, data) {<br>  if (err) throw err;<br>    ....<br>});</pre><p>As a quick reminder, the code above is a typical use of <em>continuation-passing style (CPS)</em>functions. The CPS function, ‘fs.readFile’, takes an extra parameter, which is a callback representing the <em>continuation</em>. Once finished, the CPS, instead of returning a value to the caller, calls the continuation function, the callback, passing it the result of it’s own computation.</p><p>I don’t mind using callbacks in my code. In fact, callbacks are great for things such as representing side effects or event notification, but once your start using them to manage your control flow, you’re trapped. Why ? because they do not compose.</p><p>So let’s just ask “What’s the meaning, <em>the denotation</em> or the return value of the above function ?”. The answer is ‘undefined’. And we can’t do anything useful with ‘undefined’, apart from testing that it’s actually … undefined.</p><p>The problem is that, inside the callback, you’ve been teleported to another flow of execution and this is a one way ticket.</p><p>Think of callbacks as the famous <a href="https://en.wikipedia.org/wiki/Black_hole">Black holes</a> of physics:</p><blockquote>A black hole is a mathematically defined region of spacetime exhibiting such a strong gravitational pull that no particle or electromagnetic radiation can escape from it</blockquote><p>Particularly</p><blockquote><em>In many ways a black hole acts like an ideal black body, as it reflects no light</em></blockquote><p>Callback functions, also, reflect no light in a program flow.</p><p>If later, while trapped inside the first callback, you use another callback style function, then you lose the second <em>flow</em> and you fall into another hole. The more you use callbacks, the more you sink into hell.</p><p>So how can we move forward in our code without falling into black holes?</p><p>The answer is <em>composition</em>. But to use composition, we must get something from a function, and we know that CPS functions do not reflect anything. So we must, someway, make them return something. But what value are they supposed to return ? Well this is the motivation for this article.</p><p>Even if you are already aware of existing <a href="https://hackernoon.com/tagged/javascript">JavaScript</a> solutions. I, strongly, recommend you to go through this post. You’ll see the power of denotational (ie functional) thinking and how it allows us to derive clean and concise semantics for those solutions.</p><h4>Welcome to the future</h4><p>If we think about those functions: file read operations, network requests, DOM events, … what do they have in common?</p><p>They describe operations that can not be achieved in <em>the immediate</em>, I mean we can not afford to wait for their completion in our current program flow (like we do with normal functions). So they describe <em>future</em> results.</p><p>So let’s make them return a special type: <em>Future</em>, to denote their eventual outcome. The key idea is to have a first class value which can be passed to other functions.</p><p>What’s the meaning of a <a href="https://hackernoon.com/tagged/future">Future</a> ? it simply denotes a value who will occur after a certain time (which can be 0). The meaning of time can be an explicit event like when we say after x seconds, but can also given in relative terms, like when we say that 2 Futures complete at the same time or that a Future completes after another one.</p><p>Now this is important:</p><blockquote>Outcome of a Future always denotes an immutable value.</blockquote><p>That means, in any way we can’t change the completion value. This constraint doesn’t just simplify our implementation, it also simplifies our reasoning about its semantics.</p><p>Our Future could be implemented with a dead simple state machine. The machine starts as <em>pending</em> then evolves to <em>completed</em> and will stop here. Once completed, it’ll stay forever.</p><p>Internally, the ‘Future’ type will still rely on callbacks, but they will not serve any control flow mechanism. Instead, we’ll use them only for their right purpose: event notification.</p><pre>function Future() {<br>    // a list to store pending subscribers<br>    this.slots = [];<br>}</pre><pre>// notify completion<br>Future.prototype.ready = function(slot) {        <br>    if(this.completed)<br>        slot(this.value);<br>    else<br>        this.slots.push(slot);<br>}</pre><pre>//a simple log utility<br>function logF(f) {<br>    f.ready( v =&gt; console.log(v) );<br>}</pre><p>We provide external implementors with a method to complete the Future</p><pre>Future.prototype.complete = function(val) {<br>    // ensure immutability<br>    if(this.completed)<br>        throw &quot;Can&#39;t complete an already completed future!&quot; </pre><pre>    this.value = val;<br>    this.completed = true;</pre><pre>    // notify subscribers<br>    for(var i=0, len=this.slots.length; i&lt;len; i++) {<br>        this.slots[i](val);<br>    }</pre><pre>    // release all, we don&#39;t need this anymore<br>    this.slots = null;<br>}</pre><p>The simplest example of a Future, is one that completes <em>immediately</em> with a given value. We’ll define a method called unit with that purpose</p><pre>// unit : Value -&gt; Future&lt;Value&gt;<br>Future.unit = function(val) {<br>    var fut = new Future();<br>    fut.complete(val);<br>    return fut;<br>}</pre><pre>logF( Future.unit(&#39;hi now&#39;) );</pre><p>Above, i used a <em>type annotation</em> to makes it simple to reason about the code:</p><p>‘unit : Value → Future&lt;Value&gt;’ means simply that:</p><ol><li>‘unit’ is a function</li><li>it takes a generic type ‘Value’ as input and</li><li>returns a ‘Future’ instance holding a value of this generic type.</li></ol><p>Using the generic term ‘Value’ means we don’t actually care about the type, because the type information is irrelevant here.</p><p>another example is a value delayed by some time</p><pre>// delay: (Value, Number) -&gt; Future&lt;Value&gt;<br>Future.delay = function(v, millis) {<br>    var f = new Future();<br>    setTimeout(function(){<br>        f.complete(v);<br>    }, millis);<br>    return f;<br>}</pre><pre>logF( Future.delay(&#39;hi, it\&#39;s been 5 seconds&#39;, 5000) );</pre><p>The result of ‘delay’ is a Future that completes after a given duration with a given value.</p><p>Getting back to the ‘readFile’ example, instead of CPS functions, we can now uses a function returning a Future :</p><pre>var fs = require(&#39;fs&#39;);</pre><pre>// readFileF: (String, Object) -&gt; Future&lt;String&gt;<br>function readFileF(file, options) {<br>    var f = new Future();<br>    fs.readFile(file, options, function (err, data) {<br>      // We&#39;ll deal with errors later in the post<br>      if (err) throw err;<br>      f.complete(data);<br>    });<br>    return f;<br>}</pre><pre>logF( readFileF(&#39;test.txt&#39;, { encoding: &#39;utf8&#39;}) )</pre><p>The result of ‘readFileF’ denotes a Future holding the content of a file whose name is given as argument.</p><h4>Acting on Futures: meet our 1st guest</h4><p>You can think of ‘Future’ as a magic box holding the eventual outcome of a function.</p><p>But in order to do anything useful, we have to provide our Future type with some useful operations. Otherwise i’ll be just as if we’ve created another useless `undefined`.</p><p>So what operations can we describe in terms of Futures ?</p><p>Let’s start with computations on values held by the Future box, we’ll call it ‘fmap’ (a contraction of function map or perhaps better future map)</p><p>Here’s an example of ‘fmap’. Given a Future holding the content of a text file, we’d like to calculate the length of this content.</p><pre>var textF = readFileF(&#39;test.txt&#39;, { encoding: &#39;utf8&#39;});</pre><pre>// fmap: ( Future&lt;String&gt;, (String -&gt; Number) ) -&gt; Future&lt;Number&gt;<br>var lengthF = textF.fmap( text =&gt; text.length )<br>logF( lengthF )</pre><p>The meaning of ‘lengthF’ is a Future holding the length of a file whose content is held itself by a given Future.</p><p>To generalize, ‘fmap’ takes 2 inputs:</p><ol><li>a Future value</li><li>a mapping function over normal values.</li></ol><p>Its output is a Future holding the result of the mapping function applied to the outcome of the input Future. Note that both input and output complete at the same time.</p><p>Informally, we can describe it like this</p><pre>fmap( Future&lt;value&gt;, func ) = Future&lt; func(value) &gt;</pre><p>Implementing `fmap` is just a few lines (we’re going to define it as a method on the Future prototype)</p><pre>Future.prototype.fmap = function(fn) {<br>    var fut = new Future();<br>    this.ready(function(val) {<br>        fut.complete( fn(val) );<br>    });<br>    return fut;<br>}</pre><p>We complete the output Future when the input Future completes. And we take care of applying the mapping function.</p><p>Back to the example above, we transformed a Future holding the content of a file to another Future holding the length of this content.</p><p>Sounds familiar ? it’s quite similar to the well known map method of JavaScript arrays. Actually, it’s exactly the same concept:</p><ul><li>the ‘Array’ type is a box holding multiple values</li><li>the ‘Future’ type is a box holding a future value</li><li>‘Array.map(…)’ transforms the values inside the Array box and gives us another Array box encapsulating the transformed values</li><li>‘Future.fmap(…)’ transforms the value inside the Future box and gives us another Future box encapsulating the transformed value.</li></ul><p>So meet our 1st guest, we say both Array and Future types are <strong>Functors</strong>. That’s because they can take a normal function, apply it to whatever inside and return another instance representing the result of the transformation.</p><p>Array and Future aren’t the only Functors, whenever you encounter</p><ul><li>a type acting as a <em>context </em>for other types</li><li>knows how to apply a normal function inside it</li></ul><p>then there is a good chance that this type is a Functor.</p><p>Now that we are able to map futures to another futures. it would be be cool if we can apply functions directly to Futures like we do with normal values.</p><p>So Instead of calling</p><pre>textF.fmap( c =&gt; c.length )</pre><p>we would like to have a special kind of function ‘lengthF’ that acts directly on Futures</p><pre>// lengthF : Future&lt;String&gt; -&gt; Future&lt;Number&gt;<br>function lengthF(strF) {<br>   return strF.fmap( s =&gt; s.length )<br>}</pre><p>Looks trivial, yet we can now rewrite the file example like this</p><pre>nbCharsF = lengthF( readFileF(&#39;...&#39;) )</pre><p>We say that ‘lengthF’ is a <em>lifted</em> function. <em>Lifting</em> a function over a <em>box-type</em> like functors promotes function application from normal values to the <em>box-type</em> values. In our case, we are lifting a function ‘length: String -&gt; Number’ which acts on Strings to a function ‘lengthF: Future&lt;String&gt; -&gt; Future&lt;Number&gt;’ which acts on Futures.</p><p>To generalize, we define a function called ‘lift1’ (because it lifts only functions with arity 1, ie taking 1 input)</p><pre>Future.lift1 = function(fn) {<br>    return fut =&gt; fut.fmap(fn);<br>}</pre><p>This simple abstraction allows us to convert an asynchronous invocation into a normal function invocation. In our example ‘lengthF( readFileF(…) )’.</p><p>By composing ‘readFileF’ with ‘lengthF’ we are able to denote asynchronous computations yet without leaving the main program flow.</p><h4>How about functions with many arguments ? (or Meet our 2nd guest)</h4><p>Before we answer this question, let’s take a little time to think about a fundamental fact: What types are allowed to live inside our Future box ? do a Future have the same meaning for all types ?</p><p>The meaning of a ‘Future&lt;String&gt;’ is obvious: a value of type string that will be available in the future. Can the same reasoning be extended to all other types ? Numbers, Objects, Arrays ? certainly … How about Futures themselves ? what’s the meaning of ‘Future&lt;Future&gt;’, ie a Future of a Future ?</p><p>To get an intuition for this idea, let’s pick a simple example, we want to inspect a directory then read the content of the first file inside (for simplicity we’ll suppose there are no nested directories).</p><p>in Node we can use the async function ‘fs.readdir’ to get an array of file names inside a given directory. We’ll first derive our Future-ish function</p><pre>// readDirF : String -&gt; Future&lt; Array&lt;String&gt; &gt;<br>function readDirF(path) {<br>    var f = new Future();<br>    fs.readdir(path, (err, files) =&gt; {<br>      // hold on, it&#39;s coming<br>      if (err) throw err;<br>      f.complete(files);<br>    });<br>    return f;<br>}</pre><p>The meaning of ‘readDirF’ is a Future holding an array of the names of the files in a given directory.</p><p>In order to solve our problem, we need to</p><ol><li>Read the content of a directory which gives us a Future holding an array of Strings representing file names.</li><li>Pick the first file name then read its content.</li></ol><p>Can we use ‘fmap’ here ? let’s see what happens if we run this code in Node</p><pre>var resultF = readDirF(&quot;testdir&quot;)<br>               .fmap(files =&gt; readFileF(files[0]))</pre><pre>logF( resultF )</pre><p>And we get…oops</p><pre>{ slots: [] }</pre><p>Clearly, there is something wrong here. Instead of getting the content of the file in the console, we get the the textual representation of an object which is obviously a Future instance.</p><p>That’s because ‘fmap’ takes whatever result is returned by its mapping function and completes the output Future with it. As the mapping function above returned another Future (the result of ‘readFileF’), ‘fmap’ just blindly completed ‘resultF’ with it.</p><p>But a Future can’t complete with another Future, it has still to wait for the resulting, <em>nested </em>Future to complete before going on.</p><p>So we need a guard function to watch for this case. Instead of completing immediately, it’ll wait for the nested Future to complete.</p><p>We’ll call it ‘flatten’, because it flattens a ‘Future&lt;Future&gt;’ (a 2 layered Future) into a simple Future</p><pre>// flatten: Future&lt; Future&lt;Value&gt; &gt; -&gt; Future&lt;Value&gt;<br>Future.prototype.flatten = function() {<br>    var fut = new Future();<br>    this.ready(function(fut2) {<br>        fut2.ready( function(val){<br>            fut.complete(val);<br>        } );<br>    });<br>    return fut;<br>}</pre><p>And we can get our result like this</p><pre>var result = <br>  readDirF(&quot;testdir&quot;)<br>    .fmap(files =&gt; readFileF(files[0], {encoding: &#39;utf8&#39;}))</pre><pre>logF( result.flatten() )</pre><p>Instead of calling ‘fmap’ and ‘flatten’ each time, we’ll pack this use case in a single call: an ad-hoc function that will do both operations : map to a 2 Layered Future then flatten it. To stay meaningful, we’ll name it ‘flatMap’ (awful, i know)</p><pre>Future.prototype.flatMap = function( fn ) {<br>    return this.fmap(fn).flatten();<br>}</pre><p>Conceptually, what we described above is a way of <em>sequencing</em> 2 dependent computations, ‘readFileF’ depends on ‘readDirF’ because the first function takes its input (file name) from the outcome of the second function (list of file names).</p><p>Now let me introduce our second guest, Besides being a Functor, a Future is also a <strong>Monad</strong>, because it defines a way for describing a computation as a sequence of steps. using the above ‘flatMap’ method we can chain together multiple function calls with each step taking its input from the previous step.</p><p>As for Functors, there are many use cases for Monads; technically, all a Monad needs is</p><ul><li>a way of lifting a normal value to a <em>Monadic</em> one: in our example, it’s the ‘Future.unit’ which makes a Future from a normal value.</li><li>a way of chaining 2 consecutive operations: each Monad has its proper logic of chaining. In our case, the logic is handled with ‘flatMap’ which is to wait for the completion of a Future before moving forward.</li></ul><p>We’ve seen that the 2nd operation (flatMap) can also be defined in terms of 2 other operations (‘fmap’ and ‘flatten’), if you have a Functor which defines an ‘fmap’ function, all you need is a flattening operation to simplify a 2 layered structure.</p><p>So now, let’s return to the main question, how can we lift a function that takes multiple arguments to act on Futures?</p><p>Let’s pick the file example again, this time we would like to concatenate the content of all files in a given directory, our code will look like</p><pre>// concatF : (Future&lt;String&gt;, ...) -&gt; Future&lt;String&gt;<br>var resultF = concatF( text1F, text1F, ...)</pre><p>What is the meaning of the above function? The result denotes a Future holding the concatenation of all strings held by the input Futures. Logically, ‘concatF’ needs to wait for all the input Futures in order to proceed, so the output completes when all inputs compete.</p><p>for implementation, We’ll start with the case of 2 arguments</p><pre>// lift2: ( (a, b) -&gt; c) -&gt; ( (Future&lt;a&gt;, Future&lt;b&gt;) -&gt; Future&lt;c&gt;)<br>Future.lift2 = function(fn) {<br>    return (fut1, fut2) =&gt; {<br>        fut1.flatMap( value1 =&gt;<br>            fut2.flatMap( value2 =&gt; <br>                Future.unit( fn(value1, value2) );<br>            )<br>        )<br>    };<br>}</pre><p>In spite of the appearances, the code’s logic is rather simple, let’s go step by step:</p><ul><li>‘Future.lift2’ takes a “function which acts on 2 normal values” and returns a “function which acts on 2 Futures”</li><li>What the returned (lifted) function does actually is</li><li>use ‘flatMap’ to sequence 2 operations (with a nested call),</li><li>the first operation does nothing by itself, it just binds the first outcome to the variable ‘value1’ which remains visible in the scope</li><li>the second , nested, operation, apply the function fn to the 2 outcomes: ‘value1’ and ‘value2’</li><li>since ‘fn’ returns a normal value, and ‘flatMap’ expects a Future value, we use ‘Future.unit’ to lift the normal result to a Future result.</li></ul><p>The trick here is: run ‘flatMap’ on all Futures in sequence allows the function to wait on all futures, and nested ‘flatMap’ calls gives the function a scope for all completion values.</p><p>The last use of ‘Future.unit’ to lift the result suggests that multi-argument lifted functions are different from <em>Monadic</em> ones which describes sequential operations (like ‘readFile’ inside ‘readDir’).</p><p>Here is an example that concatenates the content of 2 files</p><pre>var concat2F = Future.lift2( (str1, str2) =&gt; str1+&#39; &#39;+str2 );</pre><pre>var text1F = readFileF(&#39;test1.txt&#39;, {encoding: &#39;utf8&#39;});<br>var text2F = readFileF(&#39;test2.txt&#39;, {encoding: &#39;utf8&#39;});</pre><pre>logF( concat2F(text1F, text2F) );</pre><p>Note that even in the case of the second Future ‘text2F’ completes before the first ‘text1F’, the function has still to wait for ‘text1F’. Upon its completion, the function will proceed immediately because ‘text2F’ has already completed.</p><p>We can conclude that a multi-argument function does not depend on the order of completion of its inputs, nor their interdependence. In fact, we can also reformulate this meaning like this:</p><ul><li>if ‘fmap’ denotes a single operation, and</li><li>‘flatMap’ denotes sequential operations, then</li><li>multi-argument lifted functions denotes <em>parallel</em> operations.</li></ul><p>That makes sense, because, like in the example above, we run the Futures all at once and wait for their completion before proceeding to the computation.</p><p>We can easily extend the the pattern used in lift2 to lift3 or lift4, but we’ll just generalize to an arbitrary number of arguments, all we need is the 2 tricks from above: nesting and scoping</p><pre>function toArray(args) {<br>  return Array.prototype.slice.call(args);<br>}</pre><pre>Future.lift = function(fn) {<br>  return function() {            <br>    var futArgs = toArray(arguments), // our future arguments<br>        ctx = this; // save context (&#39;this&#39;)</pre><pre>    return bindArg(0, []);</pre><pre>    function bindArg(index, valArgs) {        <br>      // wait the current Future argument        <br>      return futArgs[index].flatMap(function(val) {  <br>        // collect completion values               <br>        valArgs= valArgs.concat(val);</pre><pre>        // not yet the last Future argument ?<br>        return (index &lt;  futArgs.length - 1) ?                  <br>          // flatMap (wait) the next argument<br>          bindArg(index+1, valArgs) : <br>         <br>          // last reached, apply the collected vales<br>          Future.unit( fn.apply(ctx, valArgs) ); <br>      });           <br>    }<br>  }<br>}</pre><p>‘lift’ reuse the same trick used in ‘lift2’. Since we don’t know in advance the exact number of inputs, we use a recursive call to iterate over all of them, waiting for their completion then collecting the outcomes on the way (wait/flatMap Future at index, then save the completion value and repeat the process with the next Future input until all inputs are processed). Once we reach the last input Future in the chain we proceed to function application, then we return the lifted result.</p><blockquote>We could have used another structure called ‘Applicative Functor’ to implement n-ary lifting. But then we’d have to go through some explanations involving terms like lambdas and currying, so will just skip this today.</blockquote><h4>Error handling</h4><p>Recall in our process of converting ‘fs.readFile’ how we’ve ignored the error value</p><pre>function readFileF(file, options) {<br>    var f = new Future();<br>    fs.readFile(file, options, function (err, data) {          <br>      if (err) throw err;<br>      ...</pre><p>We can’t do that in a real code. Because we’re not in the main program flow (the outest), there is no way for us to catch the error. In the case above, the error propagates upward and finding no handler in the way, Node just aborts the whole program.</p><p>What if we need instead to catch the error to have a chance to fix it, or possibly redirect it to somewhere like a meaningful error message for the user.</p><p>A possible solution is to augment the semantics of Future with the notion of <em>failure</em>. Until now we didn’t gave any meaning to the outcome of a Future, but now we’ll think of Future as a context with 2 possible outcomes (completion or failure), so we have to review the semantics in the context of a possible failure.</p><p>First, we had a method ready to notify completion so we also define a method to notify failure.</p><pre>function Future() {<br>    this.slots = [];<br>    this.failslots = [];<br>}</pre><pre>Future.prototype.failed = function(slot) {<br>    if(this.hasFailed)<br>        slot(this.error);<br>    else<br>        this.failslots.push(slot);<br>}</pre><p>We also define a method to fail the future.</p><pre>Future.prototype.fail = function(err) {  <br>    if(this.completed || this.hasFailed)<br>        throw &quot;Can&#39;t fail an already settled future!&quot;        <br>    this.hasFailed = true;<br>    this.error = err;<br>    for(var i=0, len=this.failslots.length; i&lt;len; i++) {<br>        this.failslots[i](err);<br>    }<br>}</pre><p>Now what’s the new meaning of the ‘fmap’ operation ?</p><p>In the example ‘readFileF(…).fmap( s =&gt; s.length)’, No meaning can be given to the length of a non existing file. Logically, we’d like to transform only valid results so the output Future will complete with a transformed value only if the input Future completed with success, otherwise it’ll just fail with the same error. Also, if the mapping function failed in its transformation, we must also fail the output.</p><pre>Future.prototype.fmap = function(fn) {<br>    var fut = new Future();<br>    this.ready( val =&gt; {            <br>        try        { fut.complete( fn(val) );    }<br>        catch(err) { fut.fail(err);              }          <br>    });</pre><pre>    this.failed( err =&gt; fut.fail(err) );</pre><pre>    return fut;<br>}</pre><p>For ‘flatten’ it’s a little more complicated. We have 2 futures : outer and inner, and each one has also 2 possible outcomes : completion or failure. That gives us 4 cases to handle (2x2)</p><pre>Future.prototype.flatten = function() {<br>    var fut = new Future();</pre><pre>    // 1- outer fails &amp;&amp; inner fails =&gt; output fails<br>    // 2- outer fails &amp;&amp; inner completes =&gt; output fails<br>    this.failed( _ =&gt; fut.fail(err) );</pre><pre>    // 3- outer completes &amp;&amp; inner fails =&gt; output fails <br>    this.ready( fut2 =&gt;<br>        fut2.failed( err =&gt; fut.fail(err) );           <br>    ); </pre><pre>    // 4- outer completes &amp;&amp; inner completes =&gt; output completes<br>    this.ready( fut2 =&gt;<br>        fut2.ready( val =&gt; fut.complete(val) );<br>    );      <br>    return fut;<br>}</pre><p>In the case of ‘flatten’, the output completes only and only if both inner and outer inputs complete.</p><p>We don’t have to modify ‘flatMap’ or ‘lift’. Since they are derived from ‘fmap’ and ‘flatten’, they automatically inherit their error handling semantics.</p><p>Ok, we made our future skip all subsequent computations in case of failure, which leaves us with a failed Future. So what operations can we do with a failed Future ?</p><p>There is only one, we can <em>catch</em> future errors and try to fix them, how ? by defining an operation that can transform a failed Future to a completed one, which can then be reintegrated again in our computation.</p><p>We’ll have to define a <em>peer</em> function for ‘fmap’, we’ll call it ‘fmapError’. It’s like a flipped version of fmap</p><pre>Future.prototype.fmapError = function(fn) {<br>    var fut = new Future();<br>    this.ready( val =&gt; fut.complete(val)  );<br>    this.failed( err =&gt; {<br>        try         { fut.complete( fn(err) );    }<br>        catch(err1) { fut.fail( err1 );           }            <br>    });<br>    return fut;<br>}</pre><p>‘fmapError’ acts as an async catch statement, valid results pass through the function while errors are caught and sent in to the mapping function.</p><p>Here is a simple example</p><pre>readFileF(&#39;unknown file&#39;).fmapError( err =&gt; &#39;alternate content&#39; )</pre><p>But what if you we want to catch errors in a monadic fashion, ie inside a pipeline of sequential operations ?</p><p>For this, we’ll define flatMapError which is nothing more than the <em>peer</em> version of flatMap.</p><pre>Future.prototype.flatMapError = function( fn ) {<br>    return this.fmapError(fn).flatten();<br>}</pre><p>As an example of use, suppose we are trying to fetch some content from some web URL that can be sometimes unavailable, upon a failure of our request, we’ll try an alternative URL, we can use ‘flatMapError’ to catch the first failure and return the alternative request</p><pre>resultF = requestF(&#39;/url1&#39;).flatMapError( err =&gt; requestF(&#39;/url2&#39;) )</pre><p>The meaning of ‘resultF’ is a Future whose content is the outcome of the first request to ‘url1’ in case of a success and the outcome of the second request to ‘url2’ if the first request failed.</p><h4>Side effects</h4><p>We’ve defined all needed operations to describe computations in a composable way. Using the so far defined functions, we can work with asynchronous functions in a simple synchronous style, passing our Futures around as if they were normal values.</p><p>But each computation has to reach an end. That’s the right time to do our side effects operations: updating our UI, logging into the console, saving to a database…</p><p>A quick temptation is to define a special method ‘do’ to denote this type of operations. But then we have, as usual, to ask <em>what is the meaning of do, what’s its return value ?</em></p><p>If we simply make it return a Future with no value transformation, then it’ll have the same denotation as ‘future.fmap( Id )’ (Id being the identity function x =&gt; x); But we know actually they are not the same. <em>We should not have this kind of distortions in our abstract model: things that denotes the same thing are just supposed to be the same thing.</em></p><p>Another question is related to the meaning of time: does ‘do’ complete in the same time as the input Future ? What if our side effect operation consist of sending updates to a remote server ? we should wait for the server response. Morever the server response can (and it’s often) be relevant to our app.</p><p>In fact, it’s clear from the above, that side effect operations are nothing more than functions that are <em>chained </em>to a given Future and returns themselves another Future. This is precisely the denotation of ‘flatMap’ and ‘flatMapError’. Put another way, side effect operations are just Monadic functions (if you have some Haskell background, you’ve probably made the link to the <em>IO Monad</em>).</p><h4>So what’s the point about Promises</h4><p>If you are already aware of Promises, then you obviously noted the similarities between Futures and Promises, you may have also noted how I avoided to mention them all the way.</p><p>If you want, take the Future class, mix together fmap, flatMap, mapError and flatMapError into a single big monolithic method and you’ll end up with something more or less similar to the ‘Promise.then’ method.</p><p>Of course, There will be always someone to argue that implementing a <a href="https://web.archive.org/web/20150405010543/https://promisesaplus.com/">Fully compliant specification</a> of Promises is far more complicated. He may even tell me something like <a href="https://blog.domenic.me/youre-missing-the-point-of-promises">You’re Missing the Point of Promises</a>.</p><p>If you take a minute to read the above Promise/A+ specification, you’ll notice it doesn’t describe the Promise operations in terms of the values they denote but rather describes a process to be followed by any compliant implementation. Put another way, the specification is operational and not denotational. Operational semantics are strongly tied to their <em>execution model</em>. This is why, in the specification, you can notice references to things like</p><blockquote>onFulfilled or onRejected must not be called until the execution context stack contains only platform code</blockquote><p>or also references to the state internals of a promise</p><blockquote>A promise must be in one of three states: pending, fulfilled, or rejected. When pending, a promise: may transition to either the fulfilled or rejected state.</blockquote><p>In contrast to operational semantics, <em>Denotational semantics</em> do not focus on what steps should be carried out, nor the internal representation in order to achieve some computation. It rather focus on the meaning of things, and this meaning must be defined in term of other meanings that are either: well defined themselves, or fairly obvious to be defined (like values or functions).</p><p>If you understand from above that the Promise specification is useless, or that Promises themselves are useless, then <strong>You are missing the point of my article. And probably you’re also (partly) missing the point of Promises.</strong></p><p>You can always view Promises only as an imperative construct that mimics the ‘;’ (used to sequence synchronous statements), and then use them exclusively to sequence asynchronous statements. Another way is to consider them from a more functional view; ie as future values. Then you’ll start more to use them as asynchronous results of function evaluation. You’ll more and more use lifting to derive Future-ish functions and then compose those functions as you do with normal ones.</p><p>The point of this article is not to present any alternative to Promises, but essentially to demonstrate the power of denotational thinking. Along the way, we kept asking about the meaning of things and this led us to a fairly clear specification of our concept, (even if the semantics were presented in informal terms).</p><p>Using well known abstractions, like Functors and Monads, which already have solid mathematical underpinning, made it quite easy to reason about properties of Futures and derive the implementation of some operations. this may be a question of style, but i doubt we could have achieved that if we took a purely operational reasoning.</p><p><a href="https://gist.github.com/yelouafi/40aeb2a70a368acb6e45">Source code is available at this Gist</a></p><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><a href="https://goo.gl/Ahtev1"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></a></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c86d9c16cb5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/from-callback-to-future-functor-monad-6c86d9c16cb5">From Callback to Future -&gt; Functor -&gt; Monad</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>