- ReasonML Quick Start Guide
- Raphael Rafatpanah Bruno Joseph D'mello
- 522字
- 2021-07-02 12:34:12
What is ReasonML?
Let's expand on this quote. ReasonML is not a new language; it's a new syntax for the OCaml language that is meant to be familiar to JavaScript developers. Reason, as we'll call it from now on, has the exact same AST as OCaml, so Reason and OCaml only differ by syntax. The semantics are the same. By learning Reason, you're also learning OCaml. In fact, there's a command-line tool that converts between OCaml and Reason syntax, called refmt, which formats Reason/OCaml code similar to JavaScript's prettier—in fact, prettier was inspired by refmt.
OCaml is a general-purpose programming language with an emphasis on expressiveness and safety. It was initially released in 1996 and has an advanced type system that helps catch your mistakes without getting in the way. Like JavaScript, OCaml features garbage collection for automatic memory management and first-class functions that can be passed around as arguments to other functions.
Reason is also a toolchain that makes getting started easier for those coming from a JavaScript background. This toolchain allows us to take advantage of both the JavaScript and OCaml ecosystems. We will dive deeper here in Chapter 2, Setting Up a Development Environment. For now, we'll experiment directly in the online playground by visiting Reason's online playground at https://reasonml.github.io/try.
Try typing in this Hello World example into the online playground:
let message = "World";
Js.log("Hello " ++ message);
There are two things you'll notice:
- The OCaml syntax is automatically generated in the lower-left section of the editor (not shown)
- The Reason/OCaml code is compiled to JavaScript directly in the browser:
// Generated by BUCKLESCRIPT VERSION 3.2.0, PLEASE EDIT WITH CARE
'use strict';
var message = "World";
console.log("Hello World");
exports.message = message;
/* Not a pure module */
You may be wondering how the Reason/OCaml code is being compiled from within the browser. BuckleScript, Reason's partner project, compiles the OCaml AST to JavaScript. Since Reason and OCaml both get converted into the same OCaml AST, BuckleScript supports both Reason and OCaml. Furthermore, since BuckleScript is itself written in OCaml, it can be compiled to JavaScript and run directly in the browser.
Inspecting the compiled JavaScript reveals just how readable it is. Looking closer, you'll notice that the compiled output has also been optimized: within the console.log statement, the "Hello World" string has been inlined directly instead of using the message variable.
Notably, BuckleScript also supports string interpolation (https://bucklescript.github.io/docs/en/common-data-types.html#interpolation):
/* The message variable is interpolated */
{j|Hello $message|j}