<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ reasonml - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ reasonml - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 25 Aug 2026 16:18:29 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/reasonml/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Learn the ReasonML programming language ]]>
                </title>
                <description>
                    <![CDATA[ ReasonML is an object-functional programming language created at Facebook. ReasonML lets you write simple, fast and quality type safe code while leveraging both the JavaScript & OCaml ecosystems. In this full course from David Kopal, you will learn e... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-reasonml-full-course/</link>
                <guid isPermaLink="false">66b2050043f24c1bb159816e</guid>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ reasonml ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Tue, 02 Apr 2019 20:19:38 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/ghost/2019/04/reason.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>ReasonML is an object-functional programming language created at Facebook. ReasonML lets you write simple, fast and quality type safe code while leveraging both the JavaScript &amp; OCaml ecosystems.</p>
<p>In this full course from David Kopal, you will learn everything you need to know about ReasonML (aka Reason) and you will be able to start building awesome things with it.</p>
<p>You can watch the full video course on the <a target="_blank" href="https://www.youtube.com/watch?v=sjWsAYJF8BA">freeCodeCamp.org YouTube channel</a> (5.5 hour watch).</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Psst! Here’s why ReasonReact is the best way to write React ]]>
                </title>
                <description>
                    <![CDATA[ By David Kopal Are you using React to build user interfaces? Well, I am too. And now, you’ll learn why you should write your React applications using ReasonML. React is a pretty cool way to write user interfaces. But, could we make it even cooler? Be... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/psst-heres-why-reasonreact-is-the-best-way-to-write-react-5088d434d035/</link>
                <guid isPermaLink="false">66d45e07230dff01669057c1</guid>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ reasonml ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 20 Sep 2018 17:10:34 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*jU57ThAZc50pyAG1INey3g.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By David Kopal</p>
<p>Are you using <a target="_blank" href="https://reactjs.org/">React</a> to build user interfaces? Well, I am too. And now, you’ll learn why you should write your React applications <a target="_blank" href="https://medium.freecodecamp.org/learn-reasonml-by-building-tic-tac-toe-in-react-334203dd513c">using ReasonML</a>.</p>
<p>React is a pretty cool way to write user interfaces. But, could we make it even cooler? Better?</p>
<p>To make it better, we need to identify its problems first. So, what is the main problem of React as a JavaScript library?</p>
<h3 id="heading-react-wasnt-initially-developed-for-javascript"><strong>React wasn’t initially developed for JavaScript</strong></h3>
<p>If you take a closer look at React, you’ll see that some of its main principles are foreign to JavaScript. Let’s talk about immutability, functional programming principles, and type system in particular.</p>
<p>Immutability is one of the core principles of React. You don’t want to mutate your props or your state because if you do, you might experience unpredictable consequences. In JavaScript, we don’t have immutability out of the box. We are keeping our data structures immutable by a convention, or we use libraries such as <a target="_blank" href="https://facebook.github.io/immutable-js/">immutableJS</a> to achieve it.</p>
<p>React is based on the principles of functional programming since its applications are compositions of functions. Although JavaScript has some of these features, such as first-class functions, it’s not a functional programming language. When we want to write some nice declarative code, we need to use external libraries like <a target="_blank" href="https://github.com/lodash/lodash/wiki/FP-Guide">Lodash/fp</a> or <a target="_blank" href="https://ramdajs.com/">Ramda</a>.</p>
<p>So, what’s up with the type system? In React, we had <a target="_blank" href="https://reactjs.org/docs/typechecking-with-proptypes.html">PropTypes</a>. We’ve used them to mimic the types in JavaScript since it isn’t a statically typed language itself. To take advantage of advanced static typing, we again need to use external dependencies, such as <a target="_blank" href="https://flow.org/">Flow</a> and <a target="_blank" href="https://www.typescriptlang.org/">TypeScript</a>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/MBTOborji3cqg5Fulhsv9cA3tiEoSi8fu3l4" alt="Image" width="800" height="450" loading="lazy">
<em>React, and JavaScript comparison</em></p>
<p>As you can see, <strong>JavaScript isn’t compatible with React’s core principles.</strong></p>
<p>Is there another programming language that would be more compatible with React than JavaScript?</p>
<p>Fortunately, we have <a target="_blank" href="https://reasonml.github.io/">ReasonML</a>.</p>
<p>In Reason, we get immutability out of the box. Since it’s based on <a target="_blank" href="https://ocaml.org/">OCaml</a>, the functional programming language, we have such features built into the language itself as well. Reason also provides us with a strong type system on its own.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/QHbj6LVoIlCNOKjfeZdBDkRBClnsL1qnz5kr" alt="Image" width="800" height="450" loading="lazy">
<em>React, JavaScript, and Reason comparison</em></p>
<p>Reason is compatible with React’s core principles.</p>
<h3 id="heading-reason">Reason</h3>
<p>It isn’t a new language. It’s an alternative JavaScript-like syntax and toolchain for OCaml, a functional programming language that’s been around for more than 20 years. Reason was created by Facebook developers who already used OCaml in their projects (<a target="_blank" href="https://github.com/facebook/flow">Flow,</a> <a target="_blank" href="https://github.com/facebook/infer">Infer</a>).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/iZOPlVop1OKOO36dranfKTTg9P0b0PGtCR6x" alt="Image" width="225" height="225" loading="lazy"></p>
<p>Reason, with its C-like syntax, makes OCaml approachable for people coming from mainstream languages such as JavaScript or Java. It provides you with better documentation (compared to OCaml) and a <a target="_blank" href="https://reasonml.github.io/docs/en/community">growing community</a> around it. Plus, it makes it easier to integrate with your existing JavaScript codebase.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/FeHSk51tA2kwbv2sVbu-QinVHCzYipvQUMWp" alt="Image" width="240" height="240" loading="lazy"></p>
<p>OCaml serves as a backing language for Reason. Reason has the same semantics as OCaml — only the syntax is different. This means that you can write OCaml using Reason’s JavaScript-like syntax. As a result, you can take advantage of OCaml’s awesome features, such as its strong type system and pattern matching.</p>
<p>Let’s take a look at an example of Reason’s syntax.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> fizzbuzz = <span class="hljs-function">(<span class="hljs-params">i</span>) =&gt;</span>
  <span class="hljs-keyword">switch</span> (i mod <span class="hljs-number">3</span>, i mod <span class="hljs-number">5</span>) {
  | <span class="hljs-function">(<span class="hljs-params"><span class="hljs-number">0</span>, <span class="hljs-number">0</span></span>) =&gt;</span> <span class="hljs-string">"FizzBuzz"</span>
  | <span class="hljs-function">(<span class="hljs-params"><span class="hljs-number">0</span>, _</span>) =&gt;</span> <span class="hljs-string">"Fizz"</span>
  | <span class="hljs-function">(<span class="hljs-params">_, <span class="hljs-number">0</span></span>) =&gt;</span> <span class="hljs-string">"Buzz"</span>
  | <span class="hljs-function"><span class="hljs-params">_</span> =&gt;</span> string_of_int(i)
  };
<span class="hljs-keyword">for</span> (i <span class="hljs-keyword">in</span> <span class="hljs-number">1</span> to <span class="hljs-number">100</span>) {
  Js.log(fizzbuzz(i))
};
</code></pre>
<p>Although we’re using pattern matching in this example, it’s still pretty similar to JavaScript, right?</p>
<p>However, the only usable language for browsers is still JavaScript, meaning we need to compile to it.</p>
<h4 id="heading-bucklescript">BuckleScript</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/X36FEoHL7z2YWiiLNhNWbOy0Wx5O7FTEerBX" alt="Image" width="320" height="203" loading="lazy"></p>
<p>One of Reason’s powerful features is <a target="_blank" href="https://bucklescript.github.io/">BuckleScript compiler</a>, which takes your Reason code, and compiles it to readable and performant JavaScript with great dead code elimination. You’ll appreciate the readability if you’re working on a team where not everyone is familiar with Reason, since they’ll still be able to read the compiled JavaScript code.</p>
<p>The similarity with JavaScript is so close that some of Reason’s code doesn’t need to be changed by the compiler at all. So, you can enjoy the benefits of the statically typed language with no change to the code whatsoever.</p>
<pre><code><span class="hljs-keyword">let</span> add = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b;add(<span class="hljs-number">6</span>, <span class="hljs-number">9</span>);
</code></pre><p>This is valid code in both Reason and JavaScript.</p>
<p>BuckleScript is shipped with four libraries: the standard library called <a target="_blank" href="https://bucklescript.github.io/bucklescript/api/Belt.html">Belt</a> (<a target="_blank" href="https://discuss.ocaml.org/t/what-is-the-preferable-solution-for-the-role-of-standard-library/1092">OCaml standard library is insufficient</a>), and bindings to JavaScript, Node.js and, DOM APIs.</p>
<p>Since BuckleScript is based on OCaml compiler, you’ll get <a target="_blank" href="https://bucklescript.github.io/docs/en/build-performance">a blazingly fast compilation</a> that is much faster than Babel and several times faster than TypeScript.</p>
<p>Let’s compile our FizzBuzz algorithm written in Reason to JavaScript.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/IQVd0AQHgI7i26a21uf9kALk6xi2CzpGcoiM" alt="Image" width="800" height="450" loading="lazy">
<em>Reason’s code compilation to JavaScript through BuckleScript</em></p>
<p>As you can see, the resulting JavaScript code is pretty readable. It seems like it was written by a JavaScript developer.</p>
<p>Not only does Reason compile to JavaScript, but to native and bytecode as well. So, you can write a single application using Reason syntax and be able to run it in the browser on MacOS, Android, and iOS phones. There’s a game called <a target="_blank" href="https://github.com/jaredly/gravitron">Gravitron</a> by Jared Forsyth which is written in Reason and it can be run on all the platforms I’ve just mentioned.</p>
<h4 id="heading-javascript-interop">JavaScript interop</h4>
<p>BuckleScript also provides us with JavaScript <a target="_blank" href="https://en.wikipedia.org/wiki/Interoperability">interoperability</a>. Not only can you paste your working JavaScript code in your Reason codebase, but your Reason code can also interact with that JavaScript one. This means you can easily integrate Reason code into your existing JavaScript codebase. Moreover, you can use all the JavaScript packages from the NPM ecosystem in your Reason code. For example, you can combine Flow, TypeScript, and Reason together in a single project.</p>
<p>However, it’s not that simple. To use JavaScript libraries or code in Reason, you need to port it to Reason first via Reason bindings. In other words, you need types for your untyped JavaScript code to be able to take an advantage of Reason’ s strong type system.</p>
<p>Whenever you need to use a JavaScript library in your Reason code, check if the library was already ported to Reason by browsing the Reason Package Index (<a target="_blank" href="https://redex.github.io/">Redex</a>) database. It’s a website that aggregates different libraries and tools written in Reason and JavaScript libraries with Reason bindings. If you found your library there, you can just install it as a dependency and use it in your Reason application.</p>
<p>However, if you didn’t find your library, you’ll need to write Reason bindings yourself. If you’re just starting with Reason, keep in mind that writing bindings aren’t a thing you want to start with, since it’s one of the more challenging things in Reason’s ecosystem.</p>
<p>Fortunately, I’m just writing a post about writing Reason bindings, so stay tuned!</p>
<p>When you need some functionality from a JavaScript library, you don’t need to write the Reason bindings for a library as a whole. You can do that only for the functions or components you need to use.</p>
<h3 id="heading-reasonreact">ReasonReact</h3>
<p>This article is about writing React in Reason, which you can do thanks to the <a target="_blank" href="https://reasonml.github.io/reason-react/">ReasonReact library</a>.</p>
<p>Maybe you’re now thinking “I still don’t know why I should use React in Reason.”</p>
<p>We’ve already mentioned the main reason to do so — Reason is more compatible with React than JavaScript. Why is it more compatible? Because React was developed for Reason, or more precisely, for OCaml.</p>
<h4 id="heading-road-to-reasonreact">Road to ReasonReact</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/biX58BUYBBeSlVU4t3h4n-wBYAqi8oFUXReH" alt="Image" width="800" height="383" loading="lazy"></p>
<p>React’s first prototype was developed by Facebook and was written in Standard Meta Language (<a target="_blank" href="https://en.wikipedia.org/wiki/Standard_ML">StandardML</a>), a cousin of OCaml. Then, it was moved to OCaml. React was also transcribed to JavaScript.</p>
<p>This was because the whole web was using JavaScript, and it wasn’t probably smart to say, “Now we’ll build UI in OCaml.” And it worked — React in JavaScript has been widely adopted.</p>
<p>So, we became used to React as a JavaScript library. React together with other libraries and languages — <a target="_blank" href="https://elm-lang.org/">Elm</a>, <a target="_blank" href="https://redux.js.org/">Redux</a>, <a target="_blank" href="https://github.com/acdlite/recompose">Recompose</a>, <a target="_blank" href="https://ramdajs.com/">Ramda</a>, and <a target="_blank" href="http://www.purescript.org/">PureScript</a> — made functional programming in JavaScript popular. And with the rise of <a target="_blank" href="https://flow.org/">Flow</a> and <a target="_blank" href="https://www.typescriptlang.org/">TypeScript</a>, static typing became popular as well. As a result, the functional programming paradigm with static types became mainstream in the world of the front-end.</p>
<p>In 2016, <a target="_blank" href="https://www.bloomberg.com/company/announcements/open-source-at-bloomberg-introducing-bucklescript/">Bloomberg</a> developed and open-sourced BuckleScript, the compiler that transforms OCaml to JavaScript. This enabled them to write safe code on the front-end using OCaml’s strong type system. They took the optimized and blazingly fast OCaml compiler and swapped its back-end generating native code for a JavaScript generating one.</p>
<p>The popularity of <strong>functional programming</strong> together with the release of the BuckleScript generated the ideal climate for Facebook to get back to the original idea of React, which was initially written in an <a target="_blank" href="https://en.wikipedia.org/wiki/ML_(programming_language)">ML language</a>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/XrSsanYlN4ilFGc7k97yqreJTWjNx0IQrOHl" alt="Image" width="270" height="240" loading="lazy">
<em>ReasonReact</em></p>
<p>They took OCaml semantics and JavaScript syntax, and created Reason. They also created the Reason wrapper around React — ReasonReact library — with additional functionalities such as the encapsulation of the Redux principles in stateful components. By doing so, they returned <a target="_blank" href="https://news.ycombinator.com/item?id=15209704">React to its original roots</a>.</p>
<h4 id="heading-the-power-of-react-in-reason">The power of React in Reason</h4>
<p>When React came into JavaScript, we adjusted JavaScript to React’s needs by introducing various libraries and tools. This also meant more dependencies for our projects. Not to mention that these libraries are still under development and breaking changes are introduced regularly. So you need to maintain these dependencies with care in your projects.</p>
<p>This added another layer of complexity to JavaScript development.</p>
<p>Your typical React application will have at least these dependencies:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/AAN8F1esKaCoYudXoz90QfiWd40IrF8B4IRc" alt="Image" width="800" height="450" loading="lazy"></p>
<ul>
<li>static typing — Flow/TypeScript</li>
<li>immutability — immutableJS</li>
<li>routing — ReactRouter</li>
<li>formatting — Prettier</li>
<li>linting — ESLint</li>
<li>helper function — Ramda/Lodash</li>
</ul>
<p>Let’s now swap JavaScript React for ReasonReact.</p>
<p>Do we still need all these dependencies?</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/tMqUDBPlT3UvrGwf9UqaBTXanS6QgUqEmOSi" alt="Image" width="800" height="450" loading="lazy"></p>
<ul>
<li>static typing — <strong>built-in</strong></li>
<li>immutability — <strong>built-in</strong></li>
<li>routing — <strong>built-in</strong></li>
<li>formatting — <strong>built-in</strong></li>
<li>linting — <strong>built-in</strong></li>
<li>helper functions — <strong>built-in</strong></li>
</ul>
<p>You can learn more about <a target="_blank" href="https://www.codinglawyer.io/posts/why-building-stuff-in-reason">these built-in features in my other post.</a></p>
<p>In the ReasonReact application, you don’t need these and many other dependencies since many crucial features that make your development easier are already included in the language itself. So, maintaining your packages will become easier and you don’t have an increase in complexity over time.</p>
<p>This is thanks to the OCaml, which is more than 20 years old. It’s a matured language with all of its core principles in place and stable.</p>
<h3 id="heading-wrap-up">Wrap-up</h3>
<p>At the beginning, the creators of Reason had two options. To take JavaScript and somehow make it better. By doing that they’d also need to deal with its historical burdens.</p>
<p>However, they went a different path. They took OCaml as a matured language with great performance and modified it so it resembles JavaScript.</p>
<p>React is also based on the principles of OCaml. That’s why you’ll get a much better developer experience when you’re using it with Reason. React in Reason represents a safer way of building React components, since the strong type system has got your back and you don’t need to deal with most of the JavaScript (legacy) issues.</p>
<h3 id="heading-whats-next">What’s next?</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/yD9SkLowMRhycLIc0Zz4X0VjYig9qDQb7EjK" alt="Image" width="800" height="533" loading="lazy"></p>
<p>If you’re coming from the world of JavaScript, it’ll be easier for you to get started with Reason, due to its syntax similarity with JavaScript. If you’ve been programming in React, it’ll be even easier for you since you can use all your React knowledge as ReasonReact has the same mental model as React and very similar workflow. This means you don’t need to start from scratch. You’ll learn Reason as you develop.</p>
<p>The best way to start using Reason in your projects is to do it incrementally. I’ve already mentioned that you can take Reason code and use it in JavaScript, and the other way around. You can do the same thing with ReasonReact. You take your ReasonReact component and use it in your React JavaScript application, and vice versa.</p>
<p>This incremental approach has been chosen by Facebook developers who are using Reason extensively in the development of <a target="_blank" href="https://reasonml.github.io/blog/2017/09/08/messenger-50-reason.html">the Facebook Messenger app</a>.</p>
<p>If you want to build an application using React in Reason and learn the basics of Reason in a practical way, check my other article where <a target="_blank" href="https://medium.freecodecamp.org/learn-reasonml-by-building-tic-tac-toe-in-react-334203dd513c">we’ll build a Tic Tac Toe game together.</a></p>
<p>If you have any questions, criticism, observations, or tips for improvement, feel free to write a comment below or reach me via <a target="_blank" href="https://twitter.com/coding_lawyer">Twitter</a> or <a target="_blank" href="https://www.codinglawyer.io/">my blog</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn ReasonML by building Tic Tac Toe in React ]]>
                </title>
                <description>
                    <![CDATA[ By David Kopal 3. 7. 2018: UPDATED to ReasonReact v0.4.2 You may have heard of Reason before. It’s a syntax on top of OCaml that compiles to both readable JavaScript code and to native and bytecode as well. This means you could potentially write a ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-reasonml-by-building-tic-tac-toe-in-react-334203dd513c/</link>
                <guid isPermaLink="false">66d45e05182810487e0ce12d</guid>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ reasonml ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 17 May 2018 17:23:12 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*-ANKA_z3Mz_RFYKRjPnSNQ.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By David Kopal</p>
<blockquote>
<p><strong><em>3. 7. 2018: UPDATED to ReasonReact v0.4.2</em></strong></p>
</blockquote>
<p>You may have heard of <a target="_blank" href="https://reasonml.github.io/">Reason</a> before. It’s a syntax on top of <a target="_blank" href="https://ocaml.org/">OCaml</a> that compiles to both readable JavaScript code and to native and bytecode as well.</p>
<p>This means you could potentially write <a target="_blank" href="https://github.com/jaredly/gravitron">a single application</a> using Reason syntax, and be able to run it in the browser, and on Android and iOS phones as well.</p>
<p>This is one of the reasons why Reason (ouch, pun) is becoming increasingly popular. This is especially true in the JavaScript community because of the syntax similarities.</p>
<p>If you were a JavaScript developer before Reason came out and wanted to learn a functional programming (FP) language, you would have had to also learn a whole new syntax and set of rules. This might’ve discouraged many people.</p>
<p>With Reason, you mainly need to understand the FP principles on which it’s based — such as immutability, currying, composition, and higher-order-functions.</p>
<p>Before I discovered Reason, I was trying to use FP principles in JavaScript as much as I could. However, JavaScript is limited in this sense, since it’s not meant to be an FP language. To take advantage of these principles effectively, you need to use a bunch of libraries that create complicated abstractions which are hidden from you.</p>
<p>Reason, on the other hand, opens the entire FP realm to all interested JavaScript developers. It provides us with an opportunity to use all those cool OCaml features using syntax we dearly know.</p>
<p>Last but not least, we can write our <a target="_blank" href="https://reasonml.github.io/reason-react/">React</a> or <a target="_blank" href="https://github.com/reasonml-community/bs-react-native">React Native</a> apps using Reason.</p>
<h3 id="heading-why-should-you-give-reason-a-try">Why should you give Reason a try?</h3>
<p>I hope you’ll discover the answer for yourself by the time you’ve finished reading this post.</p>
<p>As we go through the source code of the classic Tic Tac Toe game — written in Reason, using React — I’ll explain the core features of the language. You’ll see the benefits of the strong type system, immutability, pattern matching, functional composition using pipe, and so on. Unlike JavaScript, these features are intrinsic to Reason itself.</p>
<h3 id="heading-warming-up">Warming up</h3>
<p>Before getting your hands dirty, you need to install Reason on your machine following <a target="_blank" href="https://reasonml.github.io/docs/en/installation">this guide</a>.</p>
<p>After that, you need to setup your app. To do this, you can either clone <a target="_blank" href="https://github.com/codinglawyer/reason-tic-tac-toe">my repository</a> containing the code of our app or you can setup your own project using <a target="_blank" href="https://github.com/reasonml-community/reason-scripts">ReasonScripts</a> and code along.</p>
<p>To view your app in the browser, you need to compile your Reason files to JavaScript ones first. The <a target="_blank" href="https://bucklescript.github.io/">BuckleScript</a> compiler will take care of that.</p>
<p>In other words, when you run <code>npm start</code> (in the ReasonScripts project), your Reason code gets compiled to JavaScript. The result of the compilation is then rendered to the browser. You can see for yourself how readable the compiled code is by checking the <code>lib</code> folder inside your app.</p>
<h3 id="heading-our-first-component">Our first component</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/GBLERj-jp68NeaR1Ray8hXWUIfsItL0Gf8Y1" alt="Image" width="800" height="533" loading="lazy"></p>
<p>As we’ve already mentioned, our Tic Tac Toe app is written using <a target="_blank" href="https://github.com/reasonml/reason-react">ReasonReact</a> library. This makes Reason approachable for JavaScript developers, and a lot of newcomers are coming from this community.</p>
<p>Our app has a classic component structure, like any other React app. We’ll go through the components top-down when talking about UI, and bottom-up when describing their logic.</p>
<p>Let’s get started by taking a look at the top level <code>App</code> component.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> component = ReasonReact.statelessComponent(<span class="hljs-string">"App"</span>);
<span class="hljs-keyword">let</span> make = <span class="hljs-function"><span class="hljs-params">_children</span> =&gt;</span> {
  ...component,
  <span class="hljs-attr">render</span>: <span class="hljs-function"><span class="hljs-params">_self</span> =&gt;</span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"title"</span>&gt;</span>
         (ReasonReact.string("Tic Tac Toe"))
       <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">Game</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>,
};
</code></pre>
<p>The component gets created when you call <code>ReasonReact.statelessComponent</code> and pass the name of the component to it. You don’t need any class keywords like in React, since Reason doesn’t have any whatsoever.</p>
<p>The component is neither a class nor function — it’s a so-called <a target="_blank" href="https://reasonml.github.io/docs/en/record.html">record</a>. <code>record</code> is one of Reason’s data structures, which is similar to the JavaScript object. Unlike the latter, however, <code>record</code> is immutable.</p>
<p>Our new <code>record</code> component contains various default properties such as the initial state, lifecycle methods, and render. To adjust the component to our needs, we need to override some of these properties. We can do that inside the <code>make</code> function that returns our component.</p>
<p>Since the <code>record</code> is immutable, we can’t override its properties by mutation. Instead, we need to return a new <code>record</code>. To do this, we need to spread our component and redefine the properties we want to change. This is very similar to the JavaScript object spread operator.</p>
<p>Since the <code>App</code> is a pretty simple component, we want to override only the default <code>render</code> method so we can render our elements to the screen. The <code>render</code> method takes a single <code>self</code> argument that gives us access to the state and reducers, as we’ll see later.</p>
<p>Since ReasonReact supports <a target="_blank" href="https://reactjs.org/docs/introducing-jsx.html">JSX</a>, our <code>render</code> function can return JSX elements. The uncapitalized element will be recognized as a DOM element — <code>div</code>. The capitalized element will be recognized as a component — <code>Game</code>.</p>
<p>Due to Reason’s strong type system, you can’t simply pass a string to an element in order to display it, as you can in classic React.</p>
<p>Instead, you need to pass such string into a <code>ReasonReact.string</code> helper function that’ll convert it into <code>reactElement</code> which can be rendered.</p>
<p>Since this is a little bit verbose, and we’ll use this helper quite often, let’s store it in a <code>toString</code> variable. In Reason, you can use only the <code>let</code> keyword to do that.</p>
<pre><code><span class="hljs-keyword">let</span> toString = ReasonReact.string;
</code></pre><p>Before moving any further, let’s talk a bit about the <code>make</code> function’s arguments. Since we are not passing any props to the <code>App</code> component, it takes only the default <code>children</code> argument.</p>
<p>However, we are not using it. We can make this explicit by writing an underscore before it. If we haven’t done this, the compiler would give us a warning that the argument is not being used. We are doing the same with the <code>self</code> argument in the <code>render</code> method.</p>
<p>Understandable error and warning messages are another cool feature that’ll improve your developer experience, compared to JavaScript.</p>
<h3 id="heading-setting-up-variant-types">Setting up variant types</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/BH-VorOdK3kCiMmNYWKwfWWeSwUFBLKgYI1m" alt="Image" width="800" height="534" loading="lazy"></p>
<p>Before diving into the application itself, we’ll define our types first.</p>
<p>Reason is a statically typed language. This means it evaluates the types of our values during the compilation time. In other words, you don’t need to run your app to check if your types are correct. This also means that your editor can provide you with <a target="_blank" href="https://github.com/reasonml-editor/vscode-reasonml">useful editing support</a>.</p>
<p>However, having a type system doesn’t mean you need to explicitly define types for all the values. If you decide not to, Reason will figure out (infer) the types for you.</p>
<p>We’ll take advantage of the type system to define the types that we’ll use throughout our app. This will force us to think about the structure of our app before coding it and we’ll get a code documentation as a bonus.</p>
<p>If you’ve had any experience with <a target="_blank" href="https://www.typescriptlang.org/">TypeScript</a> or <a target="_blank" href="https://flow.org/">Flow</a>, Reason types will look familiar. However, unlike these two libraries, you don’t need any previous configuration at all (I’m looking at you Typescript). Types are available out of the box.</p>
<p>In Reason, we can distinguish between <a target="_blank" href="https://reasonml.github.io/docs/en/type.html">types</a> and <a target="_blank" href="https://reasonml.github.io/docs/en/variant.html">variant types</a> (in short variants). Types are for example <code>bool</code>, <code>string</code>, and <code>int</code>. On the other hand, variants are more complex. Think of them as of enumerable sets of values—or more precisely, constructors. Variants can be processed via pattern matching, as we’ll see later.</p>
<pre><code>type player =
  | Cross
  | Circle;

type field =
  | Empty
  | Marked(player);
</code></pre><p>Here we define <code>player</code> and <code>field</code> <strong>variants</strong>. When defining a variant, you need to use a <code>type</code> keyword.</p>
<p>Since we are building a Tic Tac Toe game, we’ll need two players. So, the <code>player</code> type will have two possible constructors — <code>Cross</code> and <code>Circle</code>.</p>
<p>If we think about the playing board, we know that each <code>field</code> type can have two possible constructors — either <code>Empty</code> or <code>Marked</code> by one of the players.</p>
<p>If you take a look at the <code>Marked</code> constructor, you can see that we are using it as a data structure. We use a variant to hold another piece of data. In our case, we pass it the <code>player</code> variant. This behavior is pretty powerful since it enables us to combine different variants and types together to create more complex types.</p>
<p>So, we’ve got the <code>field</code> variant. However, we need to define the whole playing board which consists of rows of fields.</p>
<pre><code>type row = list(field);
type board = list(row);
</code></pre><p>Each <code>row</code> is a list of <code>field</code>s and the playing <code>board</code> is composed of a list of <code>row</code>s.</p>
<p>The <code>list</code> is one of Reason’s data structures—similar to the JavaScript array. The difference is, it’s immutable. Reason also has an <code>array</code> as a mutable fixed-length list. We’ll come back to these structures later.</p>
<pre><code>type gameState = 
  | Playing(player)
  | Winner(player)
  | Draw;
</code></pre><p>Another variant we need to define is a <code>gameState</code>. The game can have three possible states. One of the <code>player</code>s can be <code>Playing</code>, be a <code>Winner</code>, or we can have a <code>Draw</code>.</p>
<p>Now, we have all the types we need to compose the state of our game.</p>
<pre><code class="lang-jsx">type state = {
  board,
  gameState,
};
</code></pre>
<p>Our component’s state is a <code>record</code> composed of the <code>board</code> and the <code>gameState</code>.</p>
<p>Before moving any further, I’d like to talk about modules. In Reason, files are modules. For example, we stored all our variants inside <code>SharedTypes.re</code> file. This code gets automatically wrapped inside the module like this:</p>
<pre><code class="lang-jsx"><span class="hljs-built_in">module</span> SharedTypes {
  <span class="hljs-comment">/* variant types code */</span>
}
</code></pre>
<p>If we wanted to access this module in a different file, we don’t need any <code>import</code> keyword. We can easily access our modules anywhere in our app using the dot notation — for example <code>SharedTypes.gameState</code>.</p>
<p>Since we are using our variants quite often, we can make it more concise by writing <code>open SharedTypes</code> at the top of the file in which we want to access our module. This allows us to drop the dot notation since we can use our module in the scope of our file.</p>
<h3 id="heading-establishing-state">Establishing state</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/7mmAc2Jq5I1NBrtabAzNIPOTCH66gTLcvpv3" alt="Image" width="800" height="533" loading="lazy"></p>
<p>Since we know how the state of our app will look, we can start building the game itself.</p>
<p>We’ve seen that our <code>App</code> component renders the <code>Game</code> component. This is the place where all the fun starts. I’ll walk you through the code step-by-step.</p>
<p>The <code>App</code> was a stateless component, similar to the functional component in React. On the other hand, the <code>Game</code> is a stateful one which means it can contain state and reducers. Reducers in Reason are based on the same principles as those you know from <a target="_blank" href="https://github.com/reactjs/redux">Redux</a>. You call an action, and the reducer will catch it and update the state accordingly.</p>
<p>To see what’s going on in the <code>Game</code> component, let’s inspect the <code>make</code> function (the code is shortened).</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> component = ReasonReact.reducerComponent(<span class="hljs-string">"Game"</span>);

<span class="hljs-keyword">let</span> make = <span class="hljs-function"><span class="hljs-params">_children</span> =&gt;</span> {
  ...component,
  <span class="hljs-attr">initialState</span>: <span class="hljs-function">() =&gt;</span> initialState,
  <span class="hljs-attr">reducer</span>: <span class="hljs-function">(<span class="hljs-params">action: action, state: state</span>) =&gt;</span> ...,
  <span class="hljs-attr">render</span>: <span class="hljs-function">(<span class="hljs-params">{state, send}</span>) =&gt;</span> ...,
};
</code></pre>
<p>In the <code>App</code> component, we’ve overridden only the <code>render</code> method. Here, we are overriding <code>reducer</code> and <code>initialState</code> properties as well. We’ll talk about reducers later.</p>
<p><code>initialState</code> is a function that (surprisingly) returns the initial state which we stored in a variable.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> initialState = {
  <span class="hljs-attr">board</span>: [
    [Empty, Empty, Empty],
    [Empty, Empty, Empty],
    [Empty, Empty, Empty],
  ],
  <span class="hljs-attr">gameState</span>: Playing(Cross),
};
</code></pre>
<p>If you scroll up a little bit and check our <code>state</code> type, you’ll see that the <code>initialState</code> has the same structure. It’s composed of the <code>board</code> that consists of <code>row</code>s of <code>field</code>s. At the beginning of the game all fields are <code>Empty</code>.</p>
<p>However, their status may change as the game goes on. Another part of the state is the <code>gameState</code> which is initially set to the<code>Cross</code> player who plays first.</p>
<h3 id="heading-rendering-board">Rendering board</h3>
<p>Let’s take a look at the <code>render</code> method of our <code>Game</code> component.</p>
<pre><code class="lang-jsx">render: <span class="hljs-function">(<span class="hljs-params">{state, send}</span>) =&gt;</span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"game"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Board</span>
        <span class="hljs-attr">state</span>
        <span class="hljs-attr">onRestart</span>=<span class="hljs-string">(_evt</span> =&gt;</span> send(Restart))
        onMark=(id =&gt; send(ClickSquare(id)))
      /&gt;
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>,
</code></pre>
<p>We already knew that it receives the <code>self</code> argument. Here, we use destructuring to access the <code>state</code> and the <code>send</code> function. This works just like in JavaScript.</p>
<p>The render method returns the <code>Board</code> component and passes it the <code>state</code> and two state handlers as props. The first one takes care of the app restart and the second one fires when the field gets marked by a player.</p>
<p>You might’ve noticed that we aren’t writing <code>state=state</code> when passing the <code>state</code> prop. In Reason, if we are not changing the prop’s name, we can pass prop using this simplified syntax.</p>
<p>Now, we can take a look at the <code>Board</code> component. I’ve omitted most of the <code>render</code> method for the time being.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> component = ReasonReact.statelessComponent(<span class="hljs-string">"Board"</span>);

<span class="hljs-keyword">let</span> make = <span class="hljs-function">(<span class="hljs-params">~state: state, ~onMark, ~onRestart, _children</span>) =&gt;</span> {
  ...component,
  <span class="hljs-attr">render</span>: <span class="hljs-function"><span class="hljs-params">_</span> =&gt;</span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"game-board"</span>&gt;</span>
      /* ... */
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>,
};
</code></pre>
<p>The <code>Board</code> is a stateless component. As you might’ve noticed, the <code>make</code> function now takes several arguments. These are the props we’ve passed from the <code>Game</code> parent component.</p>
<p>The <code>~</code> symbol means that the argument is labeled. When calling a function with such an argument, we need to explicitly write the name of the argument when calling this function (component). And that’s what we did when we passed the props to it in the <code>Game</code> component.</p>
<p>You might’ve also noticed that we are doing another thing with one of the arguments — <code>~state:state</code>. In the previous section, we defined our <code>state</code> type. Here, we are telling the compiler that the structure of this argument should be same as of the <code>state</code> type. You might know this pattern from Flow.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/G9CmB7A70emHKIGRogQ0uKXPKrrKQw3AwjcH" alt="Image" width="800" height="533" loading="lazy"></p>
<p>Let’s come back to the <code>render</code> method of the <code>Board</code> component.</p>
<p>Since we are dealing with lists there, we’ll talk about them a little bit more now, before inspecting the rest of the <code>render</code> method.</p>
<h3 id="heading-excursion-i-list-and-array">Excursion I: list and array</h3>
<p>In Reason, we have two data structures resembling JavaScript arrays — <code>list</code> and <code>array</code>. The <code>list</code> is immutable and resizable, whereas the <code>array</code> is mutable and has a fixed length. We are using a <code>list</code> due to its flexibility and efficiency which really shines when we use it recursively.</p>
<p>To map a <code>list</code>, you can use <code>List.map</code> method that receives two arguments—a function and a <code>list</code>. The function takes an element from the <code>list</code> and maps it. This works pretty much like the JavaScript <code>Array.map</code>. Here’s a simple example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">5</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">15</span>];
<span class="hljs-keyword">let</span> increasedNumbers = List.map(<span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> num + <span class="hljs-number">2</span>, numbers);
Js.log(increasedNumbers);  <span class="hljs-comment">/* [3,[7,[10,[11,[17,0]]]]] */</span>
</code></pre>
<p>What? You’re saying that the printed result looks weird? This is because the lists in Reason are <a target="_blank" href="https://en.wikipedia.org/wiki/Linked_list">linked</a>.</p>
<p>Printing lists in your code can be confusing. Fortunately, you can convert it into an <code>array</code> using the <code>Array.of_list</code> method.</p>
<pre><code class="lang-jsx">Js.log(<span class="hljs-built_in">Array</span>.of_list(increasedNumbers));  <span class="hljs-comment">/* [3,7,10,11,17] */</span>
</code></pre>
<p>Let’s come back to our app and remind ourselves how our <code>state</code> looks.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> initialState = {
  <span class="hljs-attr">board</span>: [
    [Empty, Empty, Empty],
    [Empty, Empty, Empty],
    [Empty, Empty, Empty],
  ],
  <span class="hljs-attr">gameState</span>: Playing(Cross),
};
</code></pre>
<p>Inside the Board’s <code>render</code> method we first map over <code>board</code> which is composed of a list of rows. So, by mapping over it, we’ll gain access to the <code>row</code>s. Then, we render the <code>BoardRow</code> component.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> component = ReasonReact.statelessComponent(<span class="hljs-string">"Board"</span>);

<span class="hljs-keyword">let</span> make = <span class="hljs-function">(<span class="hljs-params">~state: state, ~onMark, ~onRestart, _children</span>) =&gt;</span> {
   ...component,
   <span class="hljs-attr">render</span>: <span class="hljs-function"><span class="hljs-params">_</span> =&gt;</span>
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"game-board"</span>&gt;</span>
         ( 
            ReasonReact.array(
               Array.of_list(
                  List.mapi(
                    (index: int, row: row) =&gt;
                     <span class="hljs-tag">&lt;<span class="hljs-name">BoardRow</span>
                        <span class="hljs-attr">key</span>=<span class="hljs-string">(string_of_int(index))</span>
                        <span class="hljs-attr">gameState</span>=<span class="hljs-string">state.gameState</span>
                        <span class="hljs-attr">row</span>
                        <span class="hljs-attr">onMark</span>
                        <span class="hljs-attr">index</span>
                     /&gt;</span>,
                   state.board,
                 ),
             ),
           )
        )
     /* ... */</span>
</code></pre>
<p>We are using the <code>List.mapi</code> method, which provides us with an <code>index</code> argument that we need to uniquely define our ids.</p>
<p>When mapping the <code>list</code> to the JSX elements, we need to do two additional things.</p>
<p>First, we need to convert it to an <code>array</code> using <code>Array.of_list</code>. Secondly, we need to convert the result to the <code>reactElement</code> using <code>ReasonReact.array</code>, since we (as already mentioned) can’t simply pass the string to the JSX element like in React.</p>
<p>To get to the field values, we need to map over each <code>row</code> as well. We are doing this inside the <code>BoardRow</code> component. Here, each element from the <code>row</code> is then mapped to the <code>Square</code> component.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> component = ReasonReact.statelessComponent(<span class="hljs-string">"BoardRow"</span>);

<span class="hljs-keyword">let</span> make = <span class="hljs-function">(<span class="hljs-params">~gameState: gameState, ~row: row, ~onMark, ~index: int, _children</span>) =&gt;</span> {
   ...component,
   <span class="hljs-attr">render</span>: <span class="hljs-function">(<span class="hljs-params">_</span>) =&gt;</span>
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"board-row"</span>&gt;</span>
         (ReasonReact.array(
            Array.of_list(
               List.mapi(
                  (ind: int, value: field) =&gt; {
                    let id = string_of_int(index) ++ string_of_int(ind);
                    <span class="hljs-tag">&lt;<span class="hljs-name">Square</span>
                       <span class="hljs-attr">key</span>=<span class="hljs-string">id</span>
                       <span class="hljs-attr">value</span>
                       <span class="hljs-attr">onMark</span>=<span class="hljs-string">(()</span> =&gt;</span> onMark(id))
                       gameState
                    /&gt;;
                 },
               row,
             ),
          ),
        ))
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>,
};
</code></pre>
<p>Using these two mappings, our board gets rendered. You’ll agree with me that the readability of this code isn’t so good because of all the function wrappings.</p>
<p>To improve it, we can use the <code>pipe</code> operator which takes our <code>list</code> data and pipes it through our functions. Here’s the second mapping example — this time using <code>pipe</code>.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> component = ReasonReact.statelessComponent(<span class="hljs-string">"BoardRow"</span>);

<span class="hljs-keyword">let</span> make = <span class="hljs-function">(<span class="hljs-params">~gameState: gameState, ~row: row, ~onMark, ~index: int, _children</span>) =&gt;</span> {
   ...component,
   <span class="hljs-attr">render</span>: <span class="hljs-function">(<span class="hljs-params">_</span>) =&gt;</span>
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"board-row"</span>&gt;</span>
         (
            row
            |&gt; List.mapi((ind: int, value: field) =&gt; {
               let id = string_of_int(index) ++ string_of_int(ind
               <span class="hljs-tag">&lt;<span class="hljs-name">Square</span> 
                 <span class="hljs-attr">key</span>=<span class="hljs-string">id</span>
                 <span class="hljs-attr">value</span>
                 <span class="hljs-attr">onMark</span>=<span class="hljs-string">(()</span> =&gt;</span> onMark(id))
                 gameState
               /&gt;;
             })
            |&gt; Array.of_list
            |&gt; ReasonReact.array
         )
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>,
};
</code></pre>
<p>This makes our code much more readable, don’t you think? First, we take the <code>row</code> and pass it to the mapping method. Then, we convert our result to an <code>array</code>. Finally, we convert it to the <code>reactElement</code>.</p>
<p>By mapping our board, we are rendering a bunch of <code>Square</code> components to the screen and by doing so, we are creating the whole playing board.</p>
<p>We’re passing a couple of props to the <code>Square</code>. Since we want our <code>id</code> to be unique, we create it by combining indices from both mappings. We are also passing down the <code>value</code> which contains the <code>field</code> type that can be either <code>Empty</code> or <code>Marked</code>.</p>
<p>Finally, we pass a <code>gameState</code> and the <code>onMark</code> handler which will get invoked when a particular <code>Square</code> is clicked.</p>
<h3 id="heading-entering-fields">Entering fields</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/GEIYAkhGbe884pLggpWM4JAVEww3pR0JQYmg" alt="Image" width="800" height="529" loading="lazy"></p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> component = ReasonReact.statelessComponent(<span class="hljs-string">"Square"</span>);

<span class="hljs-keyword">let</span> make = <span class="hljs-function">(<span class="hljs-params">~value: field, ~gameState: gameState, ~onMark, _children</span>) =&gt;</span> {
  ...component,
  <span class="hljs-attr">render</span>: <span class="hljs-function"><span class="hljs-params">_self</span> =&gt;</span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>
      <span class="hljs-attr">className</span>=<span class="hljs-string">(getClass(gameState,</span> <span class="hljs-attr">value</span>))
      <span class="hljs-attr">disabled</span>=<span class="hljs-string">(gameState</span> |&gt;</span> isFinished |&gt; Js.Boolean.to_js_boolean)
      onClick=(_evt =&gt; onMark())&gt;
      (value |&gt; toValue |&gt; toString)
    <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>,
};
</code></pre>
<p>The <code>Square</code> component renders a button and passes it some props. We are using a couple of helper functions here, but I won’t talk about all of them in detail. You can find them all in the <a target="_blank" href="https://github.com/codinglawyer/reason-tic-tac-toe">repo</a>.</p>
<p>The button’s class is calculated using the <code>getClass</code> helper function which turns the square green when one of the players wins. When this happens, all the <code>Square</code>s will be disabled as well.</p>
<p>To render the button’s <code>value</code>, we use two helpers.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> toValue = <span class="hljs-function">(<span class="hljs-params">field: field</span>) =&gt;</span>
  <span class="hljs-keyword">switch</span> (field) {
  | Marked(Cross) =&gt; <span class="hljs-string">"X"</span>
  | Marked(Circle) =&gt; <span class="hljs-string">"O"</span>
  | <span class="hljs-function"><span class="hljs-params">Empty</span> =&gt;</span> <span class="hljs-string">""</span>
};
</code></pre>
<p><code>toValue</code> will convert the <code>field</code> type to the string using pattern matching. We’ll talk about pattern matching later. For now, you need to know that we are matching the <code>field</code> data to our three patterns. So, the result would be <code>X</code>, <code>O</code>, or an empty string. Then, we use <code>toString</code> to convert it to the <code>reactElement</code>.</p>
<p>Phew. We’ve just rendered the game board. Let’s quickly recap how we did it.</p>
<p>Our top-level <code>App</code> component renders the <code>Game</code> component which holds the game state and passes it down along with the handlers to the <code>Board</code> component.</p>
<p>The <code>Board</code> then takes the board state prop and maps the rows to the <code>BoardRow</code> component which maps the rows to the <code>Square</code> components. Each <code>Square</code> has an onClick handler that will fill it with a square or a circle.</p>
<h3 id="heading-make-it-do-something-already">Make it do something already!</h3>
<p>Let’s take a look at how our logic controlling the game works.</p>
<p>Since we have a board, we can allow a player to click on any square. When this happens, the <code>onClick</code> handler is fired and the <code>onMark</code> handler is called.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">/* Square component */</span>
&lt;button
  className=(getClass(gameState, value))
  disabled=(gameState |&gt; isFinished |&gt; Js.Boolean.to_js_boolean)
  onClick=(<span class="hljs-function"><span class="hljs-params">_evt</span> =&gt;</span> onMark())&gt;
  (value |&gt; toValue |&gt; toString)
&lt;/button&gt;
</code></pre>
<p>The <code>onMark</code> handler got passed from the <code>BoardRow</code> component, but it was originally defined in the <code>Game</code> component that takes care of the state.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">/* Game component */</span>
<span class="hljs-attr">render</span>: <span class="hljs-function">(<span class="hljs-params">{state, send}</span>) =&gt;</span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"game"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Board</span>
        <span class="hljs-attr">state</span>
        <span class="hljs-attr">onRestart</span>=<span class="hljs-string">(_evt</span> =&gt;</span> send(Restart))
        onMark=(id =&gt; send(ClickSquare(id)))
      /&gt;
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>,
</code></pre>
<p>We can see that the <code>onMark</code> prop is a <code>ClickSquare</code> reducer, which means we are using it to update the state (as in Redux). The <code>onRestart</code> handler works similarly.</p>
<p>Notice that we are passing square’s unique <code>id</code> to the <code>onMark</code> handler inside the <code>BoardRow</code> component.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">/* BoardRow component */</span>
(
  row
  |&gt; List.mapi(<span class="hljs-function">(<span class="hljs-params">ind: int, value: field</span>) =&gt;</span> {
    <span class="hljs-keyword">let</span> id = string_of_int(index) ++ string_of_int(ind
    &lt;Square 
      key=id
      value
      onMark=(<span class="hljs-function">() =&gt;</span> onMark(id))
      gameState
    /&gt;;
   })
  |&gt; <span class="hljs-built_in">Array</span>.of_list
  |&gt; ReasonReact.array
)
</code></pre>
<p>Before taking a look at our reducers in detail, we need to define actions to which our reducers will respond.</p>
<pre><code class="lang-jsx">type action =
  | ClickSquare(string)
  | Restart;
</code></pre>
<p>As with the global variant types, this forces us to think about our logic before we start implementing it. We define two action variants. <code>ClickSquare</code> takes one argument that will have a type of a<code>string</code>.</p>
<p>Now, let’s take a look at our reducers.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> updateBoard = <span class="hljs-function">(<span class="hljs-params">board: board, gameState: gameState, id</span>) =&gt;</span>
  board
  |&gt; List.mapi(<span class="hljs-function">(<span class="hljs-params">ind: int, row: row</span>) =&gt;</span>
    row
      |&gt; List.mapi(<span class="hljs-function">(<span class="hljs-params">index: int, value: field</span>) =&gt;</span>
        string_of_int(ind) ++ string_of_int(index) === id ?
          <span class="hljs-keyword">switch</span> (gameState, value) {
          | <span class="hljs-function">(<span class="hljs-params">_, Marked(_)</span>) =&gt;</span> value
          | (Playing(player), Empty) =&gt; Marked(player)
          | <span class="hljs-function">(<span class="hljs-params">_, Empty</span>) =&gt;</span> Empty
          } :
          value
      )
  );

reducer: <span class="hljs-function">(<span class="hljs-params">action: action, state: state</span>) =&gt;</span>
    <span class="hljs-keyword">switch</span> (action) {
    | <span class="hljs-function"><span class="hljs-params">Restart</span> =&gt;</span> ReasonReact.Update(initialState)
    | ClickSquare(<span class="hljs-function">(<span class="hljs-params">id: string</span>)) =&gt;</span>
       <span class="hljs-keyword">let</span> updatedBoard = updateBoard(state.board, state.gameState, id);
       ReasonReact.Update({
         <span class="hljs-attr">board</span>: updatedBoard,
         <span class="hljs-attr">gameState</span>:
            checkGameState3x3(updatedBoard, state.board, state.gameState),
       });
    },
</code></pre>
<p>The <code>ClickSquare</code> reducer takes an <code>id</code> of the particular <code>Square</code>. As we’ve seen, we are passing in the <code>BoardRow</code> component. Then, our reducer calculates a new state.</p>
<p>For the <code>board</code> state update, we’ll call the <code>updateBoard</code> function. It uses the same mapping logic we used in the <code>Board</code> and <code>BoardRow</code> component. Inside of it, we map over the <code>state.board</code> to get the rows and then map over the rows to get the field values.</p>
<p>Since the <code>id</code> of each square is a composition of ids from both mappings, we’ll use it to find the field which the player clicked. When we find it, we’ll use the pattern matching to determine what to do with it. Otherwise, we’ll leave the square’s <code>value</code> unmodified.</p>
<h3 id="heading-excursion-ii-pattern-matching">Excursion II: pattern matching</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/fiLwW5agrPnevGF1Y-ZgXjbpfmEZbmE85YV1" alt="Image" width="800" height="548" loading="lazy"></p>
<p>We use the pattern matching to process our data. We define <strong>patterns</strong> which we’ll match against our <strong>data</strong>. When exercising the pattern matching in Reason, we use a <code>switch</code> statement.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">switch</span> (state.gameState, value) {
  | <span class="hljs-function">(<span class="hljs-params">_, Marked(_)</span>) =&gt;</span> value
  | (Playing(player), Empty) =&gt; Marked(player)
  | <span class="hljs-function">(<span class="hljs-params">_, Empty</span>) =&gt;</span> Empty
}
</code></pre>
<p>In our case, we are using a <a target="_blank" href="https://reasonml.github.io/docs/en/tuple.html">tuple</a> to represent our <strong>data</strong>. Tuples are data structures that separate data with commas. Our <code>tuple</code> contains the <code>gameState</code> and the <code>value</code> (containing the <code>field</code> type).</p>
<p>Then we define multiple <strong>patterns</strong> that we’ll match against our data. The first match determines the result of the entire pattern matching.</p>
<p>By writing an underscore inside the pattern, we are telling the compiler that we don’t care what the particular value is. In other words, we want to have a match every time.</p>
<p>For example, the first pattern is matched when the <code>value</code> is <code>Marked</code> by any player. So, we don’t care about the <code>gameState</code> and we don’t care about the player type either.</p>
<p>When this pattern is matched, the result is the original <code>value</code>. This pattern prevents players from overriding already marked <code>Squares</code>.</p>
<p>The second pattern addresses the situation when any player is playing, and the field is <code>Empty</code>. Here, we use the <code>player</code> type in the pattern and then again in the result. We are basically saying that we don’t care about which player is playing (<code>Circle</code> or <code>Cross</code>) but we still want to mark the square according to the player that is actually playing.</p>
<p>The last pattern acts as the default one. If the first or the second pattern isn’t matched, the third will always match. Here, we don’t care about the <code>gameState</code>.</p>
<p>However, since we’re checking for the <code>Playing</code> game state in the previous pattern, we are now checking for the <code>Draw</code> or <code>Winner</code> <code>gameState</code> type. If this is the case, we’ll leave the field <code>Empty</code>. This default scenario prevents players from continuing to play when the game is over.</p>
<p>A cool thing about pattern matching in Reason is that the compiler will warn you if you haven’t covered all the possible pattern matches. This will save you a lot of trouble, because you’ll always know if you’ve covered all the possible scenarios. So, if the compiler is not giving you any warnings, your pattern matching will never fail.</p>
<p>When the pattern matching is finished, the particular field gets updated. When all the mappings are done, we get a new board state and store it as the <code>updatedBoard</code>. We can then update the component’s state by calling <code>ReasonReact.Update</code>.</p>
<pre><code class="lang-jsx">ReasonReact.Update({
  <span class="hljs-attr">board</span>: updatedBoard,
  <span class="hljs-attr">gameState</span>:
    checkGameState3x3(updatedBoard, state.board, state.gameState),
</code></pre>
<p>We update the <code>board</code> state using the result of the pattern matching. When updating the <code>gameState</code>, we call the <code>checkGameState3x3</code> helper which calculates the state of the game for us.</p>
<h3 id="heading-do-we-have-a-winner">Do we have a winner?</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/te2QEBpX1w-XX4HghCfe543FZVCCHR5n6ma9" alt="Image" width="800" height="533" loading="lazy"></p>
<p>Let’s take a look what the <code>checkGameState3x3</code> does.</p>
<p>First, we need to define all the possible combinations of winning fields (for the 3x3 board) and store them as <code>winningCombs</code>. We also have to define the <code>winningRows</code> type.</p>
<pre><code class="lang-jsx">type winningRows = list(list(int));

<span class="hljs-keyword">let</span> winningCombs = [
  [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>],
  [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>],
  [<span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>],
  [<span class="hljs-number">0</span>, <span class="hljs-number">3</span>, <span class="hljs-number">6</span>],  
  [<span class="hljs-number">1</span>, <span class="hljs-number">4</span>, <span class="hljs-number">7</span>],
  [<span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">8</span>],
  [<span class="hljs-number">0</span>, <span class="hljs-number">4</span>, <span class="hljs-number">8</span>],
  [<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>],
];
</code></pre>
<p>We passed this list to the <code>checkGameState</code> function as the first argument.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> checkGameState3x3 = checkGameState(winningCombs);
</code></pre>
<p>By doing this, we are taking advantage of the <a target="_blank" href="https://en.wikipedia.org/wiki/Currying">currying</a> principle. When we pass the <code>winningCombs</code> to the <code>checkGameState</code> function, we get back a new function waiting for the rest of the arguments to be passed. We store this new function as the <code>checkGameState3x3</code>.</p>
<p>This behavior is really helpful, since we are able to configure the <code>checkGameState</code> function depending on the width and height of the board.</p>
<p>Let’s see what’s going on inside the <code>checkGameState</code> function.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> checkGameState =
  <span class="hljs-function">(<span class="hljs-params">
    winningRows: winningRows,
    updatedBoard: board,
    oldBoard: board,
    gameState: gameState,
  </span>) =&gt;</span>
 oldBoard == updatedBoard ?
   gameState :
   {
     <span class="hljs-keyword">let</span> flattenBoard = List.flatten(updatedBoard);
     <span class="hljs-keyword">let</span> rec check = <span class="hljs-function">(<span class="hljs-params">rest: winningRows</span>) =&gt;</span> {
       <span class="hljs-keyword">let</span> head = List.hd(rest);
       <span class="hljs-keyword">let</span> tail = List.tl(rest);
       <span class="hljs-keyword">switch</span> (
         getWinner(flattenBoard, head),
         gameEnded(flattenBoard),
         tail,
       ) {
       | <span class="hljs-function">(<span class="hljs-params">Cross, _, _</span>) =&gt;</span> Winner(Cross)
       | <span class="hljs-function">(<span class="hljs-params">Circle, _, _</span>) =&gt;</span> Winner(Circle)
       | <span class="hljs-function">(<span class="hljs-params">_, <span class="hljs-literal">true</span>, []</span>) =&gt;</span> Draw
       | <span class="hljs-function">(<span class="hljs-params">_, <span class="hljs-literal">false</span>, []</span>) =&gt;</span> whosPlaying(gameState)
       | <span class="hljs-function"><span class="hljs-params">_</span> =&gt;</span> check(tail)
       };
    };
    check(winningRows);
};
</code></pre>
<p>First, we check if the board state is different from the previous one. If that’s not the case, we’ll return the unchanged <code>gameState</code>. Otherwise, we’ll calculate the new game state.</p>
<h4 id="heading-calculating-new-states">Calculating new states</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/oanyRY03r9aMAUtxtzFR-GvsnnMoT8azntmX" alt="Image" width="800" height="600" loading="lazy"></p>
<p>We start determining our new game state by converting the <code>board</code> part of the state, which consists of a list of rows, to a simple <code>list</code> using <code>List.flatten</code>. The flattened result will have this kind of structure:</p>
<pre><code class="lang-jsx">[Empty, Empty, Empty, Empty, Empty, Empty, Empty, Empty, Empty]
</code></pre>
<p>Back in the function, we define a <code>check</code> function that receives a single <code>rest</code> argument that has type of <code>winningRows</code> . The <code>rec</code> keyword before its definition means that it can be invoked recursively. However, for the recursive function calls, we need recursive data as well. Fortunately, the <code>list</code> is a recursive data structure.</p>
<p>We’ve already learned that lists in Reason are linked. This feature enables us to iterate through <a target="_blank" href="http://reasonmlhub.com/exploring-reasonml/ch_recursion.html">lists using recursion</a> easily.</p>
<p>At the bottom of the <code>checkGameState</code>, we call the <code>check</code> function for the first time and pass it the <code>winningCombs</code> list. Inside the function, we extract the first element from the <code>list</code> and store it as the <code>head</code>. The rest of the <code>list</code> gets stored as the <code>tail</code>.</p>
<p>After that, we use the pattern matching again. We already know how it works, so I won’t go into detail. But it’s worth checking how we define our data and patterns.</p>
<pre><code class="lang-jsx">type winner =
  | Cross
  | Circle
  | NoOne;

<span class="hljs-keyword">switch</span> (
  getWinner(flattenBoard, head),
  gameEnded(flattenBoard),
  tail,
) { ...
</code></pre>
<p>Inside the <code>switch</code> statement, we use a <code>tuple</code> again to represent our data. Our <code>tuple</code> contains three elements—winner type as a result of the <code>getWinner</code> function, boolean as a result of the <code>gameEnded</code> function, and remaining <code>list</code> elements (<code>tail</code>).</p>
<p>Before going any further, let’s talk a bit about these two helper functions.</p>
<p>We’ll take a look inside the <code>getWinner</code> function first.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> getWinner = <span class="hljs-function">(<span class="hljs-params">flattenBoard, coords</span>) =&gt;</span>
  <span class="hljs-keyword">switch</span> (
    List.nth(flattenBoard, List.nth(coords, <span class="hljs-number">0</span>)),
    List.nth(flattenBoard, List.nth(coords, <span class="hljs-number">1</span>)),
    List.nth(flattenBoard, List.nth(coords, <span class="hljs-number">2</span>)),
  ) {
  | (Marked(Cross), Marked(Cross), Marked(Cross)) =&gt; Cross
  | (Marked(Circle), Marked(Circle), Marked(Circle)) =&gt; Circle
  | <span class="hljs-function">(<span class="hljs-params">_, _, _</span>) =&gt;</span> NoOne
  };
</code></pre>
<p>When we call the <code>check</code> recursive function for the first time, the <code>head</code> will be the first element of the <code>winningRows</code>, that is <code>[0, 1, 2]</code> which is a <code>list</code>. We pass <code>head</code> to the <code>getWinner</code> function as the <code>coords</code> argument along with the <code>flattenBoard</code>.</p>
<p>Again, we use the pattern matching with the <code>tuple</code>. Inside the <code>tuple</code>, we use the <code>List.nth</code> method to access the equivalent positions of the <code>coords</code> coordinates in the flattened board <code>list</code>. The <code>List.nth</code> function takes a <code>list</code> and a number and returns the list’s element to that position.</p>
<p>So, our <code>tuple</code> consists of the three winning coordinates of our board that we’ve accessed using <code>List.nth</code>.</p>
<p>Now, we can match our <code>tuple</code> data against the patterns. The first two patterns check if all three fields are marked by the same player. If they are, we’ll return the winner — <code>Cross</code> or <code>Circle</code>. Otherwise, we’ll return <code>NoOne</code>.</p>
<p>Let’s see what’s going on inside the <code>gameEnded</code> function. It checks if all the fields are <code>Marked</code> and returns a boolean.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> gameEnded = <span class="hljs-function"><span class="hljs-params">board</span> =&gt;</span>
  List.for_all(
    <span class="hljs-function"><span class="hljs-params">field</span> =&gt;</span> field == Marked(Circle) || field == Marked(Cross),
    board,
  );
</code></pre>
<p>Since we know what values can be returned from our helper functions, let’s come back to our <code>check</code> function.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">switch</span> (
  getWinner(flattenBoard, head),
  gameEnded(flattenBoard),
  tail,
  ) {
  | <span class="hljs-function">(<span class="hljs-params">Cross, _, _</span>) =&gt;</span> Winner(Cross)
  | <span class="hljs-function">(<span class="hljs-params">Circle, _, _</span>) =&gt;</span> Winner(Circle)
  | <span class="hljs-function">(<span class="hljs-params">_, <span class="hljs-literal">true</span>, []</span>) =&gt;</span> Draw
  | <span class="hljs-function">(<span class="hljs-params">_, <span class="hljs-literal">false</span>, []</span>) =&gt;</span> whosPlaying(gameState)
  | <span class="hljs-function"><span class="hljs-params">_</span> =&gt;</span> check(tail)
  };
</code></pre>
<p>Our pattern matching can now determine if the game ended in a win or draw. If these cases are not matched, we’ll move to the following case. If it’s matched, the game will continue and the <code>whosPlaying</code> function will be called, and the other player will take a turn.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">let</span> whosPlaying = <span class="hljs-function">(<span class="hljs-params">gameState: gameState</span>) =&gt;</span>
  <span class="hljs-keyword">switch</span> (gameState) {
  | Playing(Cross) =&gt; Playing(Circle)
  | <span class="hljs-function"><span class="hljs-params">_</span> =&gt;</span> Playing(Cross)
  };
</code></pre>
<p>Otherwise, we’ll call the <code>check</code> function recursively with a new combination of winning fields.</p>
<p>That’s it. Now you know how our code controlling the game logic works.</p>
<h3 id="heading-thats-all-folks">That’s all folks!</h3>
<p>I hope this post helped you to understand the core features of this promising and still-developing language. However, to fully appreciate the power of this new syntax on top of OCaml, you need to start building your own stuff. Now you’re ready to do that.</p>
<p>Good luck!</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1zDhVxvp1uDIV-5RdNDxFMYqiyQTYNdQyC4G" alt="Image" width="800" height="533" loading="lazy"></p>
<p>If you liked this article, give it a few claps<strong>.</strong> I would greatly appreciate it and more people will be able to see this post as well.</p>
<p>This post was <a target="_blank" href="https://www.codinglawyer.io/">originally published on my blog.</a></p>
<p>If you have any questions, criticism, observations, or tips for improvement, feel free to write a comment below or reach me via <a target="_blank" href="https://twitter.com/coding_lawyer">Twitter</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
