<?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[LambdaSide - Medium]]></title>
        <description><![CDATA[Functional Programming, Lambda Programmer, Ultimate Abstraction, Mathematical Minded - Medium]]></description>
        <link>https://medium.com/lambdaside?source=rss----cbc1da9bedbe---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>LambdaSide - Medium</title>
            <link>https://medium.com/lambdaside?source=rss----cbc1da9bedbe---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 11:32:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/lambdaside" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Custom props hand-writing component without [@react.component]]]></title>
            <link>https://medium.com/lambdaside/custom-props-hand-writing-component-without-react-component-9ac8cb910b3a?source=rss----cbc1da9bedbe---4</link>
            <guid isPermaLink="false">https://medium.com/p/9ac8cb910b3a</guid>
            <category><![CDATA[reasonreact]]></category>
            <category><![CDATA[reasonml]]></category>
            <category><![CDATA[bucklescript]]></category>
            <category><![CDATA[binding]]></category>
            <dc:creator><![CDATA[digitake]]></dc:creator>
            <pubDate>Tue, 01 Sep 2020 06:51:35 GMT</pubDate>
            <atom:updated>2020-03-24T08:21:49.350Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UeZUAoKhB4QrQxTUbYpgCg.jpeg" /></figure><p>Binding ReasonReact to ReactJS is never an easy task. Sometimes, props naming gets in our way. Fortunately, ReasonML will automatically strip out name prefix or suffix with _ so that a prop name such as _open or _type turns into a corresponding open and type on JavaScript side.</p><p>However, there are still restrictions by much of ReasonML naming scheme. For example, a function’s parameters cannot begin with a capital letter, as well as the hyphen between prop name such as aria-*.</p><p>This demonstrates the problem:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fd27c21e1bee206998c26474efd333a/href">https://medium.com/media/7fd27c21e1bee206998c26474efd333a/href</a></iframe><p>Code above will not compile as aria-label and ComponentProp is not conformed to ReasonML parameter naming scheme.</p><p>To fix this, we need to create our custom makeProps and rename the props key. According to <a href="https://reasonml.github.io/reason-react/docs/en/components#hand-writing-components">Hand-writing components</a>. All we need is to define makeProps and props. The code below shows how to create those two needed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbf83408278c06b6d3a63ea6f5bd6e4f/href">https://medium.com/media/dbf83408278c06b6d3a63ea6f5bd6e4f/href</a></iframe><p>This code do quite a bit. First, it defines props with [@bs.deriving abstract]. It turns a record into an <a href="https://bucklescript.github.io/docs/en/object#abstract-record-mode">Abstract Record Mode</a>. This implies that you cannot create the record compositionally just like a normal record. Instead, it will be created via the auto-generated function of the same name props. It takes labelled arguments ending with a unit call. This is, conveniently, match the requirement of makeProps. We can then simply alias it to props.</p><p>The declaration of the type props is straightforward. [@bs.optional] says this field can be omitted. And [@bs.as &quot;&lt;name&gt;&quot;] indicates the translated name on JavaScript side. For _type we can ignore it as its behaviour will be the same, translating into type as the result code.</p><p>Lastly, the external make is used to interface to ReactJS Component. We wrapped the props type in React.component. <br>Hence, external make: React.component(props(&#39;a)) = &quot;default&quot;;</p><p>Hope this will help if you are struggling with binding ReasonReact to ReactJS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ac8cb910b3a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lambdaside/custom-props-hand-writing-component-without-react-component-9ac8cb910b3a">Custom props hand-writing component without [@react.component]</a> was originally published in <a href="https://medium.com/lambdaside">LambdaSide</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReasonML Exception Handling]]></title>
            <link>https://medium.com/lambdaside/reasonml-exception-handling-c2ea747f71df?source=rss----cbc1da9bedbe---4</link>
            <guid isPermaLink="false">https://medium.com/p/c2ea747f71df</guid>
            <category><![CDATA[exception]]></category>
            <category><![CDATA[bucklescript]]></category>
            <category><![CDATA[ocaml]]></category>
            <category><![CDATA[reasonml]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[digitake]]></dc:creator>
            <pubDate>Sat, 29 Dec 2018 11:29:43 GMT</pubDate>
            <atom:updated>2018-12-30T18:48:13.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*inYTivEpuiATD_Q3xceNgw.png" /></figure><p>One thing I found it is kinda understandable and not understandable at the same time is the lack of articles, examples or anything that mentioned how to handle an exception in ReasonML. By nature, I don’t see much use of exception writing code in ReasonML. However, It can’t be avoided when we want to interop with JavaScript.</p><p>Since I can’t find the formal grammar on ReasonML exception, I will fall back to <a href="https://caml.inria.fr/pub/docs/manual-ocaml/typedecl.html#sec170">OCaml exception</a> definition.</p><blockquote>in Ocaml, Exception is merely an <a href="http://caml.inria.fr/pub/docs/manual-ocaml/extn.html#sec266">extensible variant</a> of type<em>exn</em></blockquote><p>To handle an exception in OCaml, we can use try/with construct which resemble a pattern matching:</p><pre>try &lt;expr&gt; with<br>| &lt;pat1&gt; -&gt; &lt;expr1&gt;<br>| &lt;pat2&gt; -&gt; &lt;expr2&gt;<br>...</pre><p>In ReasonML, we use the following clause:</p><pre>try (&lt;expr&gt;) {<br>| &lt;pat1&gt; =&gt; &lt;expr1&gt;<br>| &lt;pat2&gt; =&gt; &lt;expr2&gt;<br>...<br>}</pre><p>expr is evaluated and checked. If there is an exception thrown, then it tries to match the given pattern(Keep in mind that it is a normal pattern matching with the constraint of built-in type exn). Else, the result will be an evaluation of expr. The following code is an example of how to use exception in ReasonML syntax.</p><pre>try (f) {<br>| SomeExn =&gt; doSomething()<br>| AnotherExn(value) =&gt; doSomethingWith(value)<br>...<br>}</pre><p>The pattern in the clause must be a type of exn only. We will show later that this keyword can be replaced with switch of exception type.</p><h3>Define exception type using exception keyword</h3><p>To work with exceptions, we must know how to define it first. It is simple as defining a type. In fact,exception is syntactic sugar to add a new type to exn.Consider the following code:</p><pre>type exn +=<br>  | MyError;</pre><pre>exception MyAnotherError;</pre><p>The first two lines are to add the new type called MyError using the extensible variant syntax. The line below does the same thing but using exception keyword. As we can see from the JavaScript’s counterpart:</p><pre>var MyError = Caml_exceptions.create(&quot;MyError&quot;);</pre><pre>var MyAnotherError = Caml_exceptions.create(&quot;MyAnotherError&quot;);</pre><p>The exception definition is to define any exception we want to give a meaning in our program. However, in order to deal with exceptions from JavaScript, we must handle Js.Exn.Error(t)</p><h3>Handling Exception from JavaScript side</h3><p>Most of the exceptions raised from JavaScript side will become a value of type Js.Exn.Error(t). Let assume the scenario, we want to use a JavaScript function which can throw an exception.</p><pre>exports.func = function(x) {<br>    throw new Error(&quot;My Js Error&quot;);<br>    return x;<br>}</pre><p>We need to handle this exception properly.</p><pre>[@bs.module &quot;./test.js&quot;] external func: (string) =&gt; string = &quot;func&quot;;</pre><pre>let result = try(func(&quot;test&quot;){<br>|Js.Exn.Error(err) =&gt; Js.Exn.message(err) <br>   |&gt; Js.Option.getWithDefault(&quot;Some Js Error&quot;);&quot;&quot;<br>|x =&gt; failwith(x);&quot;Other Error&quot;<br>}</pre><p>The code above imports a functionfunc which is a JavaScript function and use the construct try to test if it throws an exception. If the exception throwing is of type Js.Exn.Error, we will use Js.Exn.message to extract the error message. Otherwise, it will failwith any other type of exceptions.</p><p>Note that the result of try must be of the same type of func result, in this case, a string.</p><p>To see why, let’s unfold try into normal pattern matching. We can achieve the same behavior using a pattern matching as follows:</p><pre>[@bs.module &quot;./test.js&quot;] external func: (string) =&gt; string = &quot;func&quot;;</pre><pre>let result = switch(func(&quot;test&quot;)){<br>| exception(Js.Exn.Error(err)) =&gt; Js.Exn.message(err)<br>   |&gt; Js.Option.getWithDefault(&quot;Some Js Error&quot;);&quot;&quot;<br>| exception(x) =&gt; failwith(x);&quot;Other Error&quot;<br>| value =&gt; value<br>}</pre><p>Now things make more sense because value =&gt; value suggests that the type of this evaluation should return the value of the type of func result.</p><p>Hope this is useful when you are trying to google for ReasonML Exception Handling. That’s the whole reason while I wrote this. Feel free to leave me any comment or suggestion. Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2ea747f71df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lambdaside/reasonml-exception-handling-c2ea747f71df">ReasonML Exception Handling</a> was originally published in <a href="https://medium.com/lambdaside">LambdaSide</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On the Continuation-Passing Style and its role in FP]]></title>
            <link>https://medium.com/lambdaside/on-the-continuation-passing-style-and-its-role-in-fp-d07f151b6c5c?source=rss----cbc1da9bedbe---4</link>
            <guid isPermaLink="false">https://medium.com/p/d07f151b6c5c</guid>
            <category><![CDATA[lambda-calculus]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[cps]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[tail-recursion]]></category>
            <dc:creator><![CDATA[digitake]]></dc:creator>
            <pubDate>Sat, 16 Jun 2018 11:44:08 GMT</pubDate>
            <atom:updated>2018-06-16T17:59:51.779Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzJCjsq2qLIG-x8jjgmhfg.png" /></figure><p>In Functional Programming, We tend to use Recursion instead of an imperative loop. One tiny problem is that Recursion is normally a stack exploder. For this reason, in practice, we use <a href="https://en.wikipedia.org/wiki/Tail_call">Tail-recursion</a> form to avoid that. Tail-recursion is a way we write recursive calls in which the “caller” function value does not depend upon the “return value of callee”.</p><p>For example, consider these two different definitions of a factorial function.</p><p>f = (x) =&gt; x == 0 ? 1 : x*f(x-1);</p><p>tailF = (x, acc) =&gt; x == 0 ? acc : tailF(x-1, acc*x)</p><p>The execution chains for 3! can be shown as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*IvmanLVx-Pcht4q31wd6Sw.png" /><figcaption>The image illustrates call-chains comparison recursion vs tail-recursion.</figcaption></figure><p>The pinks indicate calls, the blue indicates return value. Tail-call normally accumulates values and pass them to the next call. As a side note, <a href="https://en.wikipedia.org/wiki/Stack_overflow">Stack overflow</a> errors are caused by the length of this chain becomes too long.</p><p>Note: Tail-call is not exactly the same thing as Tail-recursion. Tail-recursion employs Tail-call. We see they appear together just because a recursion is an obvious application of Tail-call.</p><p>In reality, the call chain of Tail-recursion may or may not be as shown. It depends on the language support of a <a href="http://2ality.com/2015/06/tail-call-optimization.html">Tail-call optimization</a>. If it isn’t, the stack will still be used.</p><p>How is that related to our topic, Continuation-Passing Style(CPS)? The answer is every call in CPS must be Tail-call. The difference is that instead of passing an <strong>accumulator</strong>, we pass a <strong>continuation</strong> to the next call.</p><p>Consider the following scenario, suppose we want to make a call to a function by the following order:</p><p>f() --&gt; g() --&gt; h()</p><p>In the imperative programming, this is easy:</p><pre>a = f()<br>b = g() + a<br>c = h() + b</pre><p>This is called a direct-style, as opposed to CPS. This program rely upon global variables, which is not a functional way of doing it i.e. it introduces a state to our program. It assumed that between a = f() and b = g() + a there is nothing else, which might not be true in the case of concurrent programming. How about h(g(f()))? Well, it is not Tail-call.</p><p><strong>CPS</strong></p><p>Let’s get back to the factorial example, how do we make that CPS? One trick to turn thing to CPS is “<strong><em>there shall be no return</em></strong>”. The tailF has a return statement. It returns acc at the base-case.</p><pre>tailF = (x, acc) =&gt; x == 0 ? acc : tailF(x-1, acc*x);</pre><p>make it CPS, we will get:</p><pre>cpsF = (x, cont) =&gt; x == 0 ? cont(1) : cpsF(x-1, y=&gt;cont(x*y));</pre><p>To see how is it different to the accumulator version, we must try to execute it. We define id = x =&gt; x as an identity function to extract final result. It will be substituted last to not make the evaluation too complicated. First, let’s try with something trivial:</p><pre>cpsF(0, id)<br>--&gt; id(1)         // by definition<br>--&gt; (x =&gt; x)(1)   // expand id<br>--&gt; (1)           // substitute x and reduce it</pre><pre>==&gt; 1 // Result</pre><p>Let’s try with 3!</p><pre>cpsF(3, id)<br>--&gt; cpsF(3-1, y=&gt;id(3*y))<br>--&gt; cpsF(<strong>2</strong>, <strong>y&#39;</strong>=&gt;id(3*<strong>y&#39;</strong>))                 // reduce and rename it</pre><pre>--&gt; cpsF(2-1, y=&gt;(y&#39;=&gt;id(3*y&#39;))(2*y))     // applied next call<br>--&gt; cpsF(<strong>1</strong>, <strong>y&#39;&#39;</strong>=&gt;(y&#39;=&gt;id(3*y&#39;))(2*<strong>y&#39;&#39;</strong>))   // reduce and rename</pre><pre>--&gt; cpsF(1-1, y=&gt;(y&#39;&#39;=&gt;(y&#39;=&gt;id(3*y&#39;))(2*y&#39;&#39;))(1*y))<br>--&gt; cpsF(<strong>0</strong>, <strong>y&#39;&#39;&#39;</strong>=&gt;(y&#39;&#39;=&gt;(y&#39;=&gt;id(3*y&#39;))(2*y&#39;&#39;))(1*<strong>y&#39;&#39;&#39;</strong>))</pre><pre>--&gt; (y&#39;&#39;&#39;=&gt;(y&#39;&#39;=&gt;(y&#39;=&gt;id(3*y&#39;))(2*y&#39;&#39;))(1*y&#39;&#39;&#39;))(1)<br>--&gt; (y&#39;&#39;=&gt;(y&#39;=&gt;id(3*y&#39;))(2*y&#39;&#39;))(1*<strong>1</strong>)<br>--&gt; (y&#39;=&gt;id(3*y&#39;))(2*<strong>(1*1)</strong>))<br>--&gt; id(3*<strong>(2*(1*1))</strong>))<br>--&gt; <strong>(x=&gt;x)</strong>(3*(2*(1*1))))<br>--&gt; (x=&gt;x)(<strong>6</strong>)<br>--&gt; <strong>(6)</strong></pre><pre>==&gt; 6 // Result</pre><p>You may observed that the execution can be divided into two phases. The expansion and the folding back. This is the main difference to accumulator style. The real computation does not happen until it finishes the expansion.</p><p>The function we send in can be an arbitrary function. It acts as the result taker and perform its own execution afterward. One major drawback we can see is it may hurt your brain.</p><p>CPS eliminates the requirement of the call stack and return statement. Instead of extract a value back, you send in your function to continue(or terminate) a program. It used to create explicit control flows in functional programming. And since it does not rely on stack value, any values will be captured inside of the continuation. We can make even more than one continuation to execute on a different execution path or even on the different CPU with no problem with mutable state. As a result, working with a concurrent program will be innately supported.</p><p>More on CPS:<br>#1 <a href="http://2ality.com/2012/06/continuation-passing-style.html">http://2ality.com/2012/06/continuation-passing-style.html</a><br>#2 <a href="https://en.wikipedia.org/wiki/Continuation-passing_style">https://en.wikipedia.org/wiki/Continuation-passing_style</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d07f151b6c5c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lambdaside/on-the-continuation-passing-style-and-its-role-in-fp-d07f151b6c5c">On the Continuation-Passing Style and its role in FP</a> was originally published in <a href="https://medium.com/lambdaside">LambdaSide</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to bind BuckleScript/ReasonML objects to JavaScript objects.]]></title>
            <link>https://medium.com/lambdaside/how-to-bind-bucklescript-reasonml-objects-to-javascript-objects-a599594f951b?source=rss----cbc1da9bedbe---4</link>
            <guid isPermaLink="false">https://medium.com/p/a599594f951b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reasonml]]></category>
            <category><![CDATA[ocaml]]></category>
            <category><![CDATA[bucklescript]]></category>
            <dc:creator><![CDATA[digitake]]></dc:creator>
            <pubDate>Tue, 08 May 2018 06:31:02 GMT</pubDate>
            <atom:updated>2018-05-08T16:45:54.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vz7wnm9GC0bD3T0xG1dKVg.png" /></figure><p><em>Note1: When I say BuckleScript in this article, I mean OCaml.<br>Note2. JavaScript object is distinct from Object in BuckleScript/ReasonML.</em></p><p>Despite they support object oriented style natively, BuckleScript/ReasonML are functional languages which means they discourage using a notion of class. Instead, to create a JavaScript object in BuckleScript/ReasonML, one might rather use Js.Dict or Record type. The former should be used when a variable number of keys is needed. The latter is used when the keys are fixed and their types are predetermined.</p><h4><strong>Create an object using </strong><strong>Js.Dict</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86d6b5a677bc2eb3e9f1444685bef88d/href">https://medium.com/media/86d6b5a677bc2eb3e9f1444685bef88d/href</a></iframe><p>Js.Dict is a JavaScript dictionary which we can put anything as a value, however, the strong type system requires its values must be of the same type. The dictionary we created will be directly converted into a plain JavaScript object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9fc0630b2916b76e94234a83106426c/href">https://medium.com/media/a9fc0630b2916b76e94234a83106426c/href</a></iframe><p>If we want to store more than one type of values in Js.Dict, we can do so using nested Js.Dict structure or a variant type. This might seems troublesome but it is a trade-off for the type-safety.</p><p>Now, let us see how to store a value of variant type in Js.Dict.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6304898b609c3f22943bc9ada1b8562/href">https://medium.com/media/d6304898b609c3f22943bc9ada1b8562/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac4da5772c54e4cf5ac41682f47a9e9f/href">https://medium.com/media/ac4da5772c54e4cf5ac41682f47a9e9f/href</a></iframe><p>The values of a Variant type does not store in the JavaScript object “<em>as-is”</em>, but they get converted and stripped out into a plain JavaScript object as shown:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/812dd1fd8983ce149fe1b47b06f0301b/href">https://medium.com/media/812dd1fd8983ce149fe1b47b06f0301b/href</a></iframe><p>Nothing becomes 0, Something becomes Block.__(0, [1]); and LotOfThing becomes Blocks.__(1, [[1,2,3]]);</p><p>This means we will not have the values of a Variant type at runtime. By running the code without looking at the comment, we cannot get back the name of Variant. This is why the annotation accessors is there. It will bind variables according to each variant type so that we can use a Variant in JavaScript side naturally, e.g. myDict[“foo”] = nothing; instead of myDict[“foo”] = /* Nothing */0;</p><h4>Create an object using Record</h4><p>While we use Js.Dict to store key and value of the same type(called fields) and it might have a variable number of fields. <a href="https://bucklescript.github.io/docs/en/object.html#object-as-record">An object can be defined as a record when it</a></p><ul><li>has a known number of fields</li><li>might or might not contain values of heterogeneous types</li></ul><p>Slightly different to Variant, a Record can be defined using type keyword with the <a href="https://realworldocaml.org/v1/en/html/records.html">following syntax</a>:</p><pre>type &lt;record-name&gt; =<br>  { &lt;field&gt; : &lt;type&gt; ;<br>    &lt;field&gt; : &lt;type&gt; ;<br>    ...<br>  }</pre><p>For example,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1257639d266e6b6366a37f3b5f43b8ab/href">https://medium.com/media/1257639d266e6b6366a37f3b5f43b8ab/href</a></iframe><p>The code above we produce an array of [&quot;John&quot;, 20, &quot;jobless&quot;] which is not quite what we want. To retain the keys, we have to wrap our Record in JavaScript object type Js.t by using object syntax.</p><p>type person = &lt; name: string; age: int; job: string &gt; Js.t</p><p>The angle bracket here is to create object in BuckleScript. Notice that this does not need a notion of Class as in typical class-based object-oriented languages. For people who came from that world, this might seems strange but in <a href="https://realworldocaml.org/v1/en/html/objects.html#ocaml-objects">OCaml type is not equal to class</a>. An object can be created without a class.</p><p>In order to create, the object of type person we can do so by</p><pre>let p = object <br>    method name = &quot;John&quot;<br>    method age = 20<br>    method job = &quot;jobless&quot;<br>end;;</pre><p>No, it was not a typo. Attributes we want to expose to external world are defined as methods. This is raw OCaml syntax for object without wrapping in Js.t. However, BuckleScript lifted all JavaScript object to be under Js.t. It helps us avoid this burden of syntax by offering bs.obj annotation. So, the chuck of code above will become</p><p>let p = [%bs.obj {name=&quot;John&quot;; age=20; job=&quot;jobless&quot;}]</p><p>ReasonML brings the syntactic sugar to another level. To define a JavaScript binding:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f9b57dcb9b7fd06484db5f216ad69db/href">https://medium.com/media/5f9b57dcb9b7fd06484db5f216ad69db/href</a></iframe><p>and to create the JavaScript object in ReasonML:</p><p>let p = {&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 20, &quot;job&quot;: &quot;jobless&quot;};</p><h4><strong>Class</strong></h4><p>JavaScript class, introduced in ES6, is mere function with fancy wiring using a prototype-based inheritance and a function closure.</p><blockquote><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes">The class syntax <strong>does not</strong> introduce a new object-oriented inheritance model to JavaScript.</a></blockquote><p>And <a href="https://bucklescript.github.io/docs/en/class.html#bind-to-js-classes">their usage is discourage</a> as:</p><blockquote><strong>In general</strong>, prefer using the previous object section’s features to bind to a JS object.</blockquote><p>Lastly, this article aims to talk about binding BuckleScript/ReasonML objects to JavaScript objects but so far what we have done is simply define structures to make OCaml type system recognise objects we are going to use.</p><p>external is a keyword to use when we want to bind a value to JavaScript value. For example:</p><p>external john : person = &quot;john&quot; [@@bs.val]</p><p>This means we bind john to the JavaScript variable name john and it has a type of person.</p><h4>Conclusion</h4><p>When working with JavaScript object, one might temping to use it with the box(of Js.t). However, to gain full benefits for OCaml type system, we rather convert Js.t into native structure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a599594f951b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lambdaside/how-to-bind-bucklescript-reasonml-objects-to-javascript-objects-a599594f951b">How to bind BuckleScript/ReasonML objects to JavaScript objects.</a> was originally published in <a href="https://medium.com/lambdaside">LambdaSide</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sweeten your Promise with Monad in ReasonML]]></title>
            <link>https://medium.com/lambdaside/sweeten-your-promise-with-monad-in-reasonml-712989fa38b?source=rss----cbc1da9bedbe---4</link>
            <guid isPermaLink="false">https://medium.com/p/712989fa38b</guid>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[reasonml]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[bucklescript]]></category>
            <dc:creator><![CDATA[digitake]]></dc:creator>
            <pubDate>Tue, 01 May 2018 21:06:37 GMT</pubDate>
            <atom:updated>2018-09-25T06:44:56.638Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ZIMMyN84B_ITRamWqDjPQ.png" /></figure><p>Promise is one of the most I found useful construct in the web programming. Because of its <a href="https://medium.com/codebuddies/getting-to-know-asynchronous-javascript-callbacks-promises-and-async-await-17e0673281ee">async nature</a>. Promise provides a nice way to put a code into synchronous chunks and each chunk is called at an <strong>asynchronous point of time</strong>.</p><p>Suppose we want to get data from two API endpoints in an orderly fashion. We should not perform a blocking call on each API fetch because it against the nature of JavaScript, Let alone that it does not even consider acceptable from a user perspective. All UI components will be unusable, and it will freeze the browser. One must have a very good reason to try to do it.</p><p>An asynchronous solution can be done with a Promise object. It will keep you a promise, to come back with a value after finish the execution. The code goes like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a62ef1c3cde88180b3dea2f09e12315/href">https://medium.com/media/4a62ef1c3cde88180b3dea2f09e12315/href</a></iframe><p>The promise object will be created by fetch command, and then the response object will be sent and appear in the next .then as a function argument. The code above is little complicated as it hits a URL first and then grab a JSON content of the URL. But I want to keep it this way to close to a real-life use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*RAUPP6UEjBUAeOv7l8hYRA.png" /><figcaption>Illustrate promise chaining</figcaption></figure><p>The image above shows how a promise object sends their results to next `.then` . The blocks represent execution context of each function. The difference to a normal function call is that they are async at the point of call but it will wait until a function resolve (or reject) is called before executing next block.</p><p>The result of Promise will be always a Promise. Even resolve is not called, Promise will take a return value and pass it to the next execution. To this point, one might feel familiar with the notion of <em>cannot escape the box. </em><strong>YES, Promise is a monad.</strong> To keep this article short, I will show that it is a monad in another article, or you can prove it yourself that it satisfies two properties, namely, return and &gt;&gt;=.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*mTOwte9huDJyXmbNkKTfcA.png" /><figcaption>Yes, Promise is a monad.</figcaption></figure><p>For now, let us get back to the title of this article. ReasonML provides a binding for Promise in Js.Promise object. We can achieve the same code above in ReasonML in this way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13fe507f227c9924643fa7502a939b9d/href">https://medium.com/media/13fe507f227c9924643fa7502a939b9d/href</a></iframe><p>The code above does the same thing as the JavaScript version. Every time we want to start a new block of execution, we have to put into then_ keyword, which is wasting time and make the code harder to read. We can put monadic expression at work to sweeten our code a bit. I defined the PromiseMonad as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a35502a2817169461aded752523898b7/href">https://medium.com/media/a35502a2817169461aded752523898b7/href</a></iframe><p>Actually, to make it become a Monad we only need return and (&gt;&gt;=) operator. defer is there just to make my life simpler to create the promise object that gonna resolve in the first place. Let us take a close look at their type</p><p>return: a&#39; =&gt; Js.Promise.t(&#39;a)</p><p>That is a simple lift, it will take any type and wrap it in the Promise type. Now let’s take a look that our workhorse, the bind function</p><p>(&gt;&gt;=): (Js.Promise.t(&#39;a),&#39;a=&gt;Js.Promise.t(&#39;b))=&gt; Js.Promise.t(&#39;b)</p><p>Trivially, it takes</p><ol><li>Promise of any type &#39;a</li><li>a <strong>function</strong> that takes the same type &#39;a that will produce a Promise of another type &#39;b.</li></ol><p>This bind functions will produce a Promise of the other type&#39;b for you!!!</p><p>Using the Monad we defined will be easy if the code doesn’t require a function call that return the value from another normal function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4321eebb0f201a04cb8bb4785fbcd451/href">https://medium.com/media/4321eebb0f201a04cb8bb4785fbcd451/href</a></iframe><p>It seems like we need another function that helps us kick start the lazy Monad. This function should take any function type and return us Promise of any type we want. That is why defer come to rescue us. The function type goes like this:</p><p>defer: (. &#39;a) =&gt; unit =&gt; &#39;b =&gt; Js.Promise.t(&#39;a)</p><p>which basically means, it takes a function and it will return a Promise object of any type that the function is return. The fancy (. &#39;a) is a ReasonML syntax that it is to create JavaScript object, not a record type. That is the requirement of make function. Maybe, it will become more clear when we see how to use it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4aab75c0e5a6eb45d31c6323bddb27c/href">https://medium.com/media/b4aab75c0e5a6eb45d31c6323bddb27c/href</a></iframe><p>defer function is generic enough to take in any function and wrap it with a nice, warm Promise.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7aed37a5742dd4ed55b4560e47b1b46b/href">https://medium.com/media/7aed37a5742dd4ed55b4560e47b1b46b/href</a></iframe><p>Lastly, we are not forget to visit the code at the top of this article and see how to rewrite that using new monadic style. As a result, we can use promise with clearer syntax and the code is now sweeter~</p><p>Note: I created <a href="https://github.com/digitake/bs-promise-monad">repo</a> for this little tool and also npm package for humanity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=712989fa38b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lambdaside/sweeten-your-promise-with-monad-in-reasonml-712989fa38b">Sweeten your Promise with Monad in ReasonML</a> was originally published in <a href="https://medium.com/lambdaside">LambdaSide</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with option using Maybe Monad]]></title>
            <link>https://medium.com/lambdaside/working-with-option-using-maybe-monad-cbb01aedcbf5?source=rss----cbc1da9bedbe---4</link>
            <guid isPermaLink="false">https://medium.com/p/cbb01aedcbf5</guid>
            <category><![CDATA[reasonml]]></category>
            <category><![CDATA[maybe]]></category>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[pattern-matching]]></category>
            <dc:creator><![CDATA[digitake]]></dc:creator>
            <pubDate>Tue, 24 Apr 2018 00:03:00 GMT</pubDate>
            <atom:updated>2018-04-24T00:36:37.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hv8dmEp-jWn_wAljJxaofg.png" /></figure><p>One of the most used type in ReasonML is option type. It represents the value which can be present( Some(x) ) or absence( None ). This type is very troublesome to whom has not used to <a href="https://en.wikipedia.org/wiki/Strong_and_weak_typing">strongly typed language</a> because it will reject any incorrect program.</p><p>Snippet below shows how we can work with option using a pattern matching.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8901420dbaae0fecf54b7e4623321f3c/href">https://medium.com/media/8901420dbaae0fecf54b7e4623321f3c/href</a></iframe><p>Pattern matching is very powerful and convenient. However, when you want to chain values, it might make code very hard to read.</p><p>Suppose we want to create a program that read three pieces of information from remote API. Each API call returns an option value, which can be None if there is no data.</p><p>The program should fail and stop work when any of the data is not available. If we want to write that in Pattern matching style, we would end up the code similar to that shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1ef1196bec8aa4c717625a61602fe10/href">https://medium.com/media/c1ef1196bec8aa4c717625a61602fe10/href</a></iframe><p>Someone might feel familiar with this code style, especially, one who works with Promise in JavaScript. The code returns &quot;No data&quot; and stops the execution when any of data in the chain is None. The difference to Promise is that this code is synchronous.</p><p>Now, let us try Monad style for the same program. First, we must define a monad module which contains return and &gt;&gt;= (bind) function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2eae7e6bfe44349f4e7edb48d6c802b/href">https://medium.com/media/d2eae7e6bfe44349f4e7edb48d6c802b/href</a></iframe><p>Function return is merely put a of type &#39;a in Some. The function that does all the job is &gt;&gt;=. This function takes value from previous option and take out the value inside, send it into function f.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88ad4e3d283518a0375158f4b7eddb9c/href">https://medium.com/media/88ad4e3d283518a0375158f4b7eddb9c/href</a></iframe><p>This code, as you can see, is easier to read. The result of the code and execution path is the same. the function will stop soon as it reaches any point in the chain with no data.</p><p>Monad is considered one of the most powerful ideas in the modern functional programming. It can be used to “box” any execution context, which, as a result, makes the easier to debug and to reason about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbb01aedcbf5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lambdaside/working-with-option-using-maybe-monad-cbb01aedcbf5">Working with option using Maybe Monad</a> was originally published in <a href="https://medium.com/lambdaside">LambdaSide</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BuckleScript vs Js_of_ocaml transpliation]]></title>
            <link>https://medium.com/lambdaside/bucklescript-vs-js-of-ocaml-transpliation-620ee8cd7f21?source=rss----cbc1da9bedbe---4</link>
            <guid isPermaLink="false">https://medium.com/p/620ee8cd7f21</guid>
            <category><![CDATA[ocaml]]></category>
            <category><![CDATA[bucklescript]]></category>
            <category><![CDATA[js-of-ocaml]]></category>
            <dc:creator><![CDATA[digitake]]></dc:creator>
            <pubDate>Tue, 17 Apr 2018 11:36:59 GMT</pubDate>
            <atom:updated>2018-04-18T06:42:19.151Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fgjgyqa21C6juz15_ADDsQ.png" /></figure><p>BuckleScript is a tool to compile from OCaml to JavaScript. It is different to <a href="https://github.com/ocsigen/js_of_ocaml">Js_of_ocaml</a> which compiles ocaml bytecode to JavaScript. Instead, BuckleScript transpiles OCaml syntax into JavaScript directly. The result is a smaller footprint and very readable code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c1cbbcc2e9c757d890ab3fa9eaf1470/href">https://medium.com/media/8c1cbbcc2e9c757d890ab3fa9eaf1470/href</a></iframe><p>Above is one-liner on OCaml hello world, now see the transpiled result from Js_of_ocaml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6365bf03c3e54dc80f29dc53a5f18b7/href">https://medium.com/media/d6365bf03c3e54dc80f29dc53a5f18b7/href</a></iframe><p>Not only the message is cryptic, it won’t run without jsoo_runtime loaded. Now take a look at the result from BuckleScript</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/267159d59ff905a0c3156a2a8dc1a15c/href">https://medium.com/media/267159d59ff905a0c3156a2a8dc1a15c/href</a></iframe><p>The BuckleScript result also depends on standard library. But look at the code it produced.</p><p>Practically, we don’t use print_string for JavaScript program. Instead, we ought to use Js.log which is the library that provided by BuckleScript. Js.log will directly be translated into console.log in JavaScript, so no overhead or library footprint.</p><p>In my opinion, BuckleScript is more suitable for web development where you start a project from scratch. But if you already have a full project in OCaml. Js_of_ocaml can be a better solution since it transplies all modules required.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=620ee8cd7f21" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lambdaside/bucklescript-vs-js-of-ocaml-transpliation-620ee8cd7f21">BuckleScript vs Js_of_ocaml transpliation</a> was originally published in <a href="https://medium.com/lambdaside">LambdaSide</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReasonML vs BuckleScript]]></title>
            <link>https://medium.com/lambdaside/reasonml-vs-bucklescript-7bca6eae7730?source=rss----cbc1da9bedbe---4</link>
            <guid isPermaLink="false">https://medium.com/p/7bca6eae7730</guid>
            <category><![CDATA[reasonml]]></category>
            <category><![CDATA[ocaml]]></category>
            <category><![CDATA[type-inference]]></category>
            <category><![CDATA[ppx]]></category>
            <category><![CDATA[bucklescript]]></category>
            <dc:creator><![CDATA[digitake]]></dc:creator>
            <pubDate>Tue, 17 Apr 2018 08:43:08 GMT</pubDate>
            <atom:updated>2018-04-18T06:39:35.242Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9vWUjdpobq2aD6IIpB0XQ.png" /></figure><p>The title is quite misleading since ReasonML is a language while BuckleScript is a tool that transpiles(a.k.a. <a href="https://en.wikipedia.org/wiki/Source-to-source_compiler">transpiler</a>) OCaml in to JavaScript.</p><p>ReasonML is merely a syntactical change of OCaml. i.e. ReasonML semantic has a bijection to OCaml semantic.</p><p><strong>Why using ReasonML then?</strong></p><p>It is closer to JavaScript syntax. This might helps interop easier for developers since they don’t have to switch their brains and switch between the two languages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2015c44e68b483255bbca2f7ee7c33b/href">https://medium.com/media/c2015c44e68b483255bbca2f7ee7c33b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5791c69f3075b39f3cad9265f9db9428/href">https://medium.com/media/5791c69f3075b39f3cad9265f9db9428/href</a></iframe><p>As you can see, the structure are the same but ReasonML look less scary to JavaScript developers.</p><p>ReasonML also provides a more natural way to define a JavaScript object while doing so in OCaml requires BuckleScript annotation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98fce49664711eff812712673a29b8de/href">https://medium.com/media/98fce49664711eff812712673a29b8de/href</a></iframe><p>The result from above is jsObj will be of type Js.t (JavaScript Object) provided by BuckleScript. <a href="https://blog.hackages.io/reasonml-ppx-8ecd663d5640">ReasonML uses </a><a href="https://blog.hackages.io/reasonml-ppx-8ecd663d5640">ppx rewriter</a> to transform this to a valid OCaml type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d9e9ba306b2bcf8ee2409d4ca9a634e/href">https://medium.com/media/8d9e9ba306b2bcf8ee2409d4ca9a634e/href</a></iframe><p>This is because OCaml treats {} as a record construct, hence to get JavaScript object as a result we must hint a compiler. The [%bs.obj ... ] is an extension node to tell BuckleScript that we want to treat a code inside as JavaScript Object. The compiler will then <a href="https://github.com/BuckleScript/bucklescript/blob/f72065034e702810ff14e3e1b68f2dfd00b65e39/jscomp/syntax/ast_exp_extension.ml#L190">expand the node</a> using ppx rewriter in the same manner as ReasonML. The result of two snippets above are identical as show below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d186f02404518047d219e02b88d888e9/href">https://medium.com/media/d186f02404518047d219e02b88d888e9/href</a></iframe><p><strong>Trivial limitation</strong></p><p>One limitation that you are likely to find funny is that you can’t directly define an empty JsObject using neitherlet x = {}; on ReasonML nor let x = [%bs.obj {}]] . This is a limitation of the type inference itself. Because the empty object can be of any type, so we must use Js.Obj.empty() instead(<a href="https://bucklescript.github.io/docs/en/object.html">ref</a>).</p><p><strong>React-support</strong></p><p>Personally, I prefer OCaml syntax. However, ReasonML is come in very handy when I write a web in React. it provides builtin React-style element support via <a href="https://reasonml.github.io/reason-react/">ReasonReact</a>. Moreover, modules from ReasonML and OCaml work together seamlessly. Practically, I tend to write a business logic in OCaml syntax while use ReasonML to handle React code.</p><p>In conclusion, ReasonML syntax lifts off some of the syntactic cumbersome for developers. It is unreasonable to not to use it when we want to develop React web with a BuckleScript. Likewise, it is also unreasonable if we try to use ReasonML ignoring the existence and roles of BuckleScript/OCaml.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bca6eae7730" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lambdaside/reasonml-vs-bucklescript-7bca6eae7730">ReasonML vs BuckleScript</a> was originally published in <a href="https://medium.com/lambdaside">LambdaSide</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>