### Install Dune Build System Source: https://reasonml.github.io/docs/en/installation Installs 'dune', a fast and friendly build system for OCaml projects. Dune simplifies building executables, libraries, and managing project configurations. ```bash opam install dune ``` -------------------------------- ### Install Reason Package Source: https://reasonml.github.io/docs/en/installation Installs the 'reason' package using opam. This command makes the Reason compiler, `refmt` (the Reason formatter), and `rtop` (an interactive Reason top-level) available. ```bash opam install reason ``` -------------------------------- ### Create and run a Reason native CLI program with esy Source: https://reasonml.github.io/docs/en/installation-esy Guides through cloning a Reason project template, installing its dependencies using esy, and then compiling and running the program. ```bash git clone https://github.com/esy-ocaml/hello-reason.git cd hello-reason # Install all dependencies (might take a while in the first run) esy # Compile and run Hello.exe esy x Hello ``` -------------------------------- ### Create opam Switch with Dependencies Source: https://reasonml.github.io/docs/en/installation Creates a new opam switch with a specified OCaml compiler version (e.g., 5.1.0) and automatically installs its dependencies. This sets up an isolated environment for ReasonML development. ```bash opam switch create . 5.1.0 --deps-only ``` -------------------------------- ### Initialize ReasonML Project with Melange Template Source: https://reasonml.github.io/docs/en/compiling-to-js-with-melange This snippet shows how to clone the official ReasonML and Melange template, initialize the opam switch, and install dependencies. It then starts the development server and a watch process for automatic recompilation. ```bash git clone https://github.com/melange-re/melange-opam-template cd melange-opam-template # Create opam switch and install dependencies make init # In separate terminals: make watch # Watch for reason file changes and recompile make serve # Run the development server ``` -------------------------------- ### Dune Executable Definition Source: https://reasonml.github.io/docs/en/installation Defines an executable named 'hello' within the Dune build system. This stanza specifies the name of the executable and its public name for installation. ```dune (executable (name hello) (public_name hello)) ``` -------------------------------- ### Check refmt Version Source: https://reasonml.github.io/docs/en/installation Verifies the installed version of `refmt`, the Reason code formatter. Ensures that the latest version is being used for code formatting and compatibility. ```bash refmt --version ``` -------------------------------- ### Initialize opam Environment Source: https://reasonml.github.io/docs/en/installation Initializes the opam package manager, creating a local directory for package storage. This command is run once to set up the opam environment. ```bash opam init -y ``` -------------------------------- ### Clone and Set Up Js_of_ocaml Template Source: https://reasonml.github.io/docs/en/compiling-to-js-with-jsoo This snippet demonstrates how to clone the `hello-jsoo-esy` template from GitHub, navigate into its directory, install dependencies using `esy`, and build the project with `npm run webpack`. This is the recommended starting point for new Js_of_ocaml projects. ```bash git clone https://github.com/jchavarri/hello-jsoo-esy.git cd hello-jsoo-esy esy npm install npm run webpack ``` -------------------------------- ### Compile and Run Dune Project Source: https://reasonml.github.io/docs/en/installation Compiles the ReasonML project using Dune and then executes the compiled program. This is a convenient command for testing and running the application. ```bash dune exec hello ``` -------------------------------- ### Install rtop REPL for ReasonML Source: https://reasonml.github.io/docs/en/rtop Installs the `rtop` package from the opam repository, enabling the use of the ReasonML REPL. This is a prerequisite for running the `rtop` command. ```bash opam install rtop ``` -------------------------------- ### ReasonML REPL (rtop) Example Session Source: https://reasonml.github.io/docs/en/rtop Demonstrates an interactive session with the `rtop` REPL, showcasing the execution of Reason code. It includes examples of variable declaration, list creation, and file loading using the `#use` directive. ```reason Welcome to utop version 2.13.1 (using OCaml version 5.0.0)! ___ _______ ________ _ __ / _ \/ __/ _ | / __/ __ \/ | / / / , _/ _// __ |\ \/ /_/ / / /_/|_/___/_/ |_|\___/\____/_/|_/ Execute statements/let bindings. Hit after the semicolon. Ctrl-d to quit. > let myVar = "Hello Reason!"; > let myList: list(string) = ["first", "second"]; > #use "./src/myFile.re"; /* loads the file into here */ Type #utop_help for help about using utop. Reason # ``` -------------------------------- ### Reason Hello World Program Source: https://reasonml.github.io/docs/en/installation A simple 'Hello World!' program written in ReasonML. It uses `print_endline` to output the message to the console. ```reason print_endline("Hello world!"); ``` -------------------------------- ### Pattern Matching with Switch in ReasonML Source: https://reasonml.github.io/docs/en/draft-blog-posts Shows an example of pattern matching using the `switch` statement in ReasonML. This demonstrates how to handle multiple conditions concisely, similar to a case analysis in mathematics. The example maps conditions to a table for clarity. ```reasonml type animal = Dog | Cat | Bird; let result = switch (isBig, myAnimal) { | (true, Dog) => 1 | (true, Cat) => 2 | (true, Bird) => 3 | (false, Dog | Cat) => 4 | (false, Bird) => 5 }; ``` -------------------------------- ### Install Melange via OPAM Source: https://reasonml.github.io/docs/en/compiling-to-js-with-melange This command installs the Melange compiler backend using the OPAM package manager. Ensure you have OCaml and OPAM set up correctly before running this command. ```bash opam install melange ``` -------------------------------- ### Activate opam Environment Source: https://reasonml.github.io/docs/en/installation Evaluates and exports environment variables from opam to make installed tools available in the current shell session. This command is typically run after initializing or switching opam environments. ```bash eval $(opam env) ``` -------------------------------- ### Build Dune Project Only Source: https://reasonml.github.io/docs/en/installation Compiles the ReasonML project using Dune without executing it. This command is used when you only want to build the project artifacts. ```bash dune build ``` -------------------------------- ### ReasonML Type Definitions and Pattern Matching with React Component Source: https://reasonml.github.io/docs/en/getting-started This snippet demonstrates ReasonML's algebraic data types (ADT) for defining different roles and uses pattern matching to provide personalized greetings. It also shows how to define a React component using the reason-react library, integrating the greeting logic. ```reason type schoolPerson = | Teacher | Director | Student(string); let greeting = person => switch (person) { | Teacher => "Hey Professor!" | Director => "Hello Director." | Student("Richard") => "Still here Ricky?" | Student(anyOtherName) => "Hey, " ++ anyOtherName ++ "."; }; module Intro = { [@react.component] let make = (~person) => {

{React.string(greeting(person))}

} }; ``` -------------------------------- ### Add opam packages using esy Source: https://reasonml.github.io/docs/en/installation-esy Demonstrates how to add packages from opam's registry using esy. Packages are prefixed with '@opam' to indicate their source. ```bash esy add @opam/bos ``` ```bash esy add @opam/reason ``` -------------------------------- ### Dune Project Configuration Source: https://reasonml.github.io/docs/en/installation Specifies the Dune language version for the project. This file is essential for Dune to understand how to build the project. ```dune (lang dune 3.6) ``` -------------------------------- ### ReasonML For Loop Example Source: https://reasonml.github.io/docs/en/loops Demonstrates a basic for loop in ReasonML that iterates from a starting integer to an ending integer, printing each number. The loop counter increments by one automatically. ```reasonml let x = 1; let y = 5; for (i in x to y) { print_int(i); print_string(" "); }; /* Prints: 1 2 3 4 5 */ ``` -------------------------------- ### Launch ReasonML REPL (rtop) Source: https://reasonml.github.io/docs/en/rtop Starts the `rtop` REPL, providing an interactive environment to evaluate Reason code. Users can define variables, execute statements, and load files within the REPL session. ```bash rtop ``` -------------------------------- ### ReasonML Interface File (.rei) Example Source: https://reasonml.github.io/docs/en/module Illustrates how interface files (`.rei`) act as module types for their corresponding implementation files (`.re`). This provides a clean separation between interface and implementation. ```reasonml /* Duration.rei */ type t; let fromSeconds: int => t; let add: (t, t) => t; /* Duration.re */ type t = int; let fromSeconds = value => value; let add = (x, y) => x + y; ``` -------------------------------- ### Install esy package manager globally Source: https://reasonml.github.io/docs/en/installation-esy Installs the esy package manager globally using npm. This is a prerequisite for managing Reason and OCaml projects with esy. ```bash npm install -g esy ``` -------------------------------- ### Reason JSX: Usage Example with Attributes Source: https://reasonml.github.io/docs/en/jsx Provides a comprehensive example of a Reason JSX component usage, showcasing various attribute types including boolean, string, integer, optional, forced optional, and event handlers. ```reason handleClick(event)}>
{"hello"}
``` -------------------------------- ### Define and Use a Basic ReasonML Module Source: https://reasonml.github.io/docs/en/module Demonstrates how to define a simple module with type definitions and functions, and how to use its members from other parts of the code. Module names must start with a capital letter. ```reasonml module Duration = { type t = int; let fromSeconds = value => value; let add = (x, y) => x + y; }; let fiveSeconds = Duration.fromSeconds(5); let tenSeconds = Duration.add(fiveSeconds, fiveSeconds); ``` -------------------------------- ### Pattern Matching with Option Type in ReasonML Source: https://reasonml.github.io/docs/en/pattern-matching Provides an example of using pattern matching with the standard `option` type in ReasonML. It demonstrates how to handle both the `Some` and `None` cases to extract values or provide defaults. ```reasonml let x: option(int) = Some(3); let value = switch (x) { | None => 0 | Some(v) => v }; ``` -------------------------------- ### ReasonML Binding Shadowing Example Source: https://reasonml.github.io/docs/en/let-binding Shows how binding shadowing can be used in ReasonML to create the appearance of updating a binding. New bindings with the same name are declared, effectively hiding the previous ones within their scope. ```reasonml let x = 10; let x = x + 10; let x = x + 3; /* x is 23 */ ``` -------------------------------- ### ReasonML Function Creation Examples Source: https://reasonml.github.io/docs/en/function Provides a cheat-sheet for creating various types of functions in ReasonML, including anonymous, named, named arguments, and optional arguments with and without default values. ```reasonml /* Anonymous function */ (x, y) => x + y /* Named function */ let add = (x, y) => x + y; /* Named arguments */ let add = (~x, ~y) => x + y; /* Non-mandatory arguments */ let add = (~x=?, ~y=?, ()) => { ... }; /* Non-mandatory with default */ let add = (~x=1, ~y=1, ()) => x + y; ``` -------------------------------- ### Access Record Fields in ReasonML Source: https://reasonml.github.io/docs/en/record Demonstrates how to access individual fields of a record instance using dot notation. This example accesses the 'name' field of the 'alice' record. ```reasonml print_endline("Hello " ++ alice.name); ``` -------------------------------- ### ReasonML Destructuring with Patterns Source: https://reasonml.github.io/docs/en/pattern-matching Shows how ReasonML patterns can be used outside of switch statements for variable declaration and data unpacking. Includes examples of destructuring tuples and records. ```reasonml let data = (1, ("red", true)); let (a, (b, _) as c) = data; /* a is 1, b is "red", c is ("red", true) */ let f = ({x, y} as p) => x + y + p.x + p.y; ``` -------------------------------- ### Login Function Returning Optional User Source: https://reasonml.github.io/docs/en/option An example of a login function that returns an 'option(person)'. It uses 'Some' to wrap the user data upon successful login, demonstrating how to represent the availability of a value. ```reasonml let login = () => Some({ name: "Alice", age: 42, }); let alice = login(); ``` -------------------------------- ### ReasonML Matching Exceptions in try Statements Source: https://reasonml.github.io/docs/en/pattern-matching Demonstrates how to match exceptions raised within a `try` block in ReasonML. Shows examples of handling specific exceptions like `IndexNegative` and `IndexOutOfBounds`. ```reasonml exception IndexNegative; exception IndexOutOfBounds; let nth = (index, items) => if (index < 0) { raise(IndexNegative); } else if (index >= Array.length(items)) { raise(IndexOutOfBounds); } else { items[index]; }; let items = [|1, 2, 3|]; let y = try (nth(-1, items)) { | IndexNegative => -1 | IndexOutOfBounds => -2 }; /* y is -1 */ ``` -------------------------------- ### ReasonML List Reversal and Length Check Source: https://reasonml.github.io/docs/en/basic-structures Shows how to reverse a list and check if it's empty in ReasonML. It also includes a note about the performance implications of getting the list length. ```reasonml let reversed = List.rev(list); let n = List.length(list); let isEmpty = list == []; ``` -------------------------------- ### Opaque Type Setup with Module Signature and Implementation in ReasonML Source: https://reasonml.github.io/docs/en/type Demonstrates the setup of an opaque type `t` within a ReasonML module. It defines a module type `Duration` with an opaque type `t` and specific functions, then provides a concrete implementation where `t` is an `int`. ```reasonml module type Duration = { /* This is an opaque type. */ type t; let fromSeconds: int => t; let add: (t, t) => t; }; module Duration: Duration = { /* Duration in seconds */ type t = int; let fromSeconds = value => value; let add = (x, y) => x + y; }; ``` -------------------------------- ### ReasonML Matching Exceptions in Switch Statements Source: https://reasonml.github.io/docs/en/pattern-matching Illustrates matching exceptions directly within a `switch` statement in ReasonML. Provides an example of handling exceptions alongside regular pattern matching. ```reasonml let y = switch (nth(-1, items)) { | 0 => "zero" | n => string_of_int(n) | exception IndexNegative => "index is negative" | exception IndexOutOfBounds => "index is too big" }; /* y is "index is negative" */ ``` -------------------------------- ### ReasonML Function Application Examples Source: https://reasonml.github.io/docs/en/function Showcases different ways to apply functions in ReasonML, including normal arguments, named arguments, named argument punning, partial application, and passing options to non-mandatory arguments. ```reasonml /* Normal arguments */ add(1, 2) /* Named arguments */ add(~x=1, ~y=2, ()) /* Named argument punning */ add(~x, ~y, ()) /* Partial application */ let addTen = add(10); /* Partial application out of order */ let half = divide(_, 2); /* Options to Non-mandatory arguments */ add(~x=?Some(1), ~y=?foo, ()) ``` -------------------------------- ### ReasonML Functor Example: Stringable Module Source: https://reasonml.github.io/docs/en/module This snippet demonstrates a basic ReasonML functor. It defines a module type 'Stringable' and a functor 'Printer' that takes a 'Stringable' module to provide printing capabilities. It then instantiates 'Printer' with an 'IntPrinter' to handle integers. ```reasonml module type Stringable = { type t; let toString: (t) => string; }; module Printer = (Item: Stringable) => { let print = (t: Item.t) => { print_endline(Item.toString(t)); }; let printList = (list: list(Item.t)) => { list |> List.map(Item.toString) |> String.concat(", ") |> print_endline; }; }; module IntPrinter = Printer({ type t = int; let toString = string_of_int; }); IntPrinter.print(10); // 10 IntPrinter.printList([1, 2, 3]); // 1, 2, 3 ``` -------------------------------- ### Reason JSX: Punning Syntax Shorthand Source: https://reasonml.github.io/docs/en/jsx Explains the concept of 'punning' in Reason JSX, where a label and its value are the same, allowing for a shorthand syntax. This is demonstrated with an example of passing multiple props concisely. ```reason Consequently, a Reason JSX component can cram in a few more props before reaching for extra libraries solutions that avoids props passing. ``` -------------------------------- ### Use Shorthand Record Construction in ReasonML Source: https://reasonml.github.io/docs/en/record Explains and demonstrates the shorthand notation for constructing records when binding names match field names exactly. This reduces redundancy in code. ```reasonml let name = "Alice"; let age = 42; /* With shorthand */ let alice = {name, age}; /* Without shorthand */ /* let alice = {name: name, age: age}; */ ``` -------------------------------- ### ReasonML 'fun' for Concise Function Matching Source: https://reasonml.github.io/docs/en/pattern-matching Explains how to use the `fun` keyword in ReasonML for creating functions that only match a single parameter. Shows an equivalent `switch` statement and its `fun` counterpart. ```reasonml let f = x => switch (x) { | Some(x) => x | None => "" }; /* equivalent */ let f = fun | Some(x) => x | None => ""; ``` -------------------------------- ### Compile Project with Dune Source: https://reasonml.github.io/docs/en/compiling-to-js-with-melange These commands compile the entire project using Dune or specifically compile only the Melange emission stanzas. Compiled JavaScript files will be located in `_build/default/app/`. ```bash dune build # Compile the entire project # or compile the melange alias (only melange.emit stanzas) dune build @melange ``` -------------------------------- ### Recursive Function Definition in ReasonML Source: https://reasonml.github.io/docs/en/function Shows the syntax for defining recursive functions in ReasonML using the 'rec' keyword. The example provides a recursive function that calls itself indefinitely. ```reasonml let rec infiniteRecursion = () => infiniteRecursion(); ``` -------------------------------- ### ReasonML Array Creation and Access Source: https://reasonml.github.io/docs/en/basic-structures Shows how to create mutable, fixed-size arrays in ReasonML and access their elements using bracket notation. It also demonstrates how to update elements. ```reasonml let arrayA = [| 1, 2, 3 |]; let first = arrayA[0]; let second = arrayA[1]; arrayA[2] = 23; ``` -------------------------------- ### Use Default Records for Initialization in ReasonML Source: https://reasonml.github.io/docs/en/record Shows a pattern for initializing records by spreading a default record and overriding specific fields. This is useful for large records with sensible defaults. ```reasonml let defaultPerson = { name: "Unknown", age: 0, }; let alice = { ...defaultPerson, name: "Alice", }; ``` -------------------------------- ### Recursive Types in ReasonML Source: https://reasonml.github.io/docs/en/recursion Illustrates how to define recursive types in ReasonML, which are recursive by default. An example of a binary tree structure is provided. The `nonrec` keyword can be used to opt-out of recursive types. ```reasonml type tree = | Leaf | Node(tree, tree); ``` ```reasonml type t = string; type nonrec t = list(t); /* t is now list(string) */ let x: t = ["hello", "world"]; ``` -------------------------------- ### Using Mutable Reference Syntax in ReasonML Source: https://reasonml.github.io/docs/en/mutable-bindings Demonstrates the built-in ReasonML syntax for working with mutable references (refs). It shows how to create a ref using `ref(value)`, access its contents with `x^`, and update its contents with `x :=`. ```reasonml let x = ref(10); x := x^ + 10; x := x^ + 3; /* x^ is 23 */ ``` -------------------------------- ### ReasonML Array Concatenation and Length Source: https://reasonml.github.io/docs/en/basic-structures Demonstrates concatenating arrays in ReasonML using `Array.append` and `Array.concat`. It also shows how to get the length of an array, noting it's a constant time operation. ```reasonml let combined = Array.append(arrayA, arrayB); let combined = Array.concat([arrayA, arrayB, arrayC]); let n = Array.length(array); ``` -------------------------------- ### ReasonML List Pattern Matching Source: https://reasonml.github.io/docs/en/basic-structures Demonstrates how to use pattern matching to deconstruct lists in ReasonML, allowing for conditional logic based on the list's structure, including checking for specific numbers of elements and remaining elements. ```reasonml switch (list) { | [first, second, ...rest] => "at least two" | [first, ...rest] => "at least one" | [] => "empty" } ``` -------------------------------- ### Using Parameterized List Type Annotations in ReasonML Source: https://reasonml.github.io/docs/en/type Demonstrates how to use the parameterized 'list' type in ReasonML with specific concrete types. Examples show annotations for a list of integers and a list of strings. ```reasonml let x: list(int) = [1, 2, 3]; let y: list(string) = ["one", "two", "three"]; ``` -------------------------------- ### ReasonML Dynamic Array Creation Source: https://reasonml.github.io/docs/en/basic-structures Shows how to dynamically create arrays in ReasonML of a specified length, initialized with a default value or generated using a function based on the index. ```reasonml let zeroes = Array.make(length, 0); let squares = Array.init(length, i => i * i); ``` -------------------------------- ### Primitive Pattern Matching in ReasonML (Booleans and Strings) Source: https://reasonml.github.io/docs/en/pattern-matching Shows examples of using primitive values (booleans and strings) directly as patterns in ReasonML's `switch` statements. This covers direct equality checks. ```reasonml switch (x) { | true => f("t") | false => g("f") }; switch (x) { | "a" => 4.0 | "tree" => 1.23 | _ => 77.5 }; ``` -------------------------------- ### Explicitly Typed Let Binding in ReasonML Source: https://reasonml.github.io/docs/en/type Illustrates how to explicitly define the type of a let binding in ReasonML using a type annotation. This example shows 'count' being declared as an 'int' with the value 42. ```reasonml let count: int = 42; ``` -------------------------------- ### Configure Dune for Melange Source: https://reasonml.github.io/docs/en/compiling-to-js-with-melange This snippet demonstrates how to configure the `dune-project` file to enable Melange support for the Dune build system. It specifies the Dune language version and includes the Melange extension. ```dune ; dune-project (dune lang 3.8) (use melange 0.1) ; Here we enable melange to work with dune ``` -------------------------------- ### Initialize Optional Person Data Source: https://reasonml.github.io/docs/en/option Demonstrates initializing an optional 'person' record with the 'None' variant. This is a common pattern for representing a state where data might not be available yet, such as before a user logs in. ```reasonml type person = { name: string, age: int, }; let nobody: option(person) = None; ``` -------------------------------- ### ReasonML Tuple Creation and Destructuring Source: https://reasonml.github.io/docs/en/basic-structures Shows how to create immutable tuples in ReasonML, which group a fixed number of heterogeneous values. It demonstrates accessing tuple elements using destructuring assignment. ```reasonml let pair = (1, "hello"); let triple = ("seven", 8, '9'); let (_, second) = pair; let (first, _, third) = triple; ``` -------------------------------- ### ReasonML Unused Pattern Warning Source: https://reasonml.github.io/docs/en/pattern-matching Illustrates ReasonML's unused pattern warning, which flags patterns that will never be matched due to preceding patterns. Shows examples of redundant patterns and how reordering them can resolve the warning. ```reasonml let x = 3; switch (x) { | 0 => "zero" | 0 => "nil" /* Warning: this match case is unused. */ | k => "another number " ++ string_of_int(k) }; ``` ```reasonml switch (x) { | k => "another number " ++ string_of_int(k) | 0 => "zero" /* Warning: this match case is unused. */ }; ``` ```reasonml /* no warning */ switch (x) { | 0 => "zero" | k => "another number " ++ string_of_int(k) }; ``` -------------------------------- ### Object/Record Definition and Access in JavaScript and Reason Source: https://reasonml.github.io/docs/en/syntax-cheatsheet Illustrates object literals and record types. JavaScript uses dynamic objects, while Reason uses statically typed records. Both support creating objects/records and accessing properties. ```javascript {x: 30, y: 20} point.x point.y = 30; {...point, x: 30} ``` ```reasonml type point = {x: int, mutable y: int} // Object literal syntax is the same {x: 30, y: 20} point.x point.y = 30; {...point, x: 30} ``` -------------------------------- ### Handle Exceptions with try/with in ReasonML Source: https://reasonml.github.io/docs/en/exception Demonstrates how to use the `try/with` construct to catch and handle exceptions. It shows how to provide a default value when a function that might throw an exception is called. ```reasonml let getItem = (theList) => if (callSomeFunctionThatThrows()) { /* return the found item here */ } else { raise(Not_found) }; let result = try (getItem([1, 2, 3])) { | Not_found => 0 /* Default value if getItem throws */ }; ``` -------------------------------- ### Defining Type Aliases in ReasonML Source: https://reasonml.github.io/docs/en/type Demonstrates how to create type aliases in ReasonML to give meaningful names to existing types. This example defines 'seconds' as an alias for 'int' and 'timeInterval' as an alias for a tuple of two 'seconds'. ```reasonml type seconds = int; type timeInterval = (seconds, seconds); ``` -------------------------------- ### Type Annotations for Variables and Functions in ReasonML Source: https://reasonml.github.io/docs/en/type Provides examples of using type annotations in ReasonML for variables, function parameters, and return types. It demonstrates explicit typing for integers, function arguments, and named arguments. ```reasonml let five: int = 5; let nine = (five: int) + (4: int); let add = (x: int, y: int): int => x + y; let drawCircle = (~radius: int): string => "hi"; ``` -------------------------------- ### Recursive Bindings in ReasonML Source: https://reasonml.github.io/docs/en/recursion Demonstrates how to opt into recursive bindings for functions in ReasonML using the `rec` keyword. This is necessary because bindings are non-recursive by default to prevent accidental infinite loops and support binding shadowing. ```reasonml let rec infiniteRecursion = () => { infiniteRecursion(); }; ``` -------------------------------- ### Illustrate Nominal Typing with Record Conversion in ReasonML Source: https://reasonml.github.io/docs/en/record Demonstrates ReasonML's nominal typing for records, where types with identical fields are not interchangeable. It shows an error when spreading a subset of fields and the correct manual conversion. ```reasonml type baby = { name: string, age: int, }; type adult = { name: string, age: int, job: string, }; let hire = (baby: baby, job): adult => { /* Error: Unexpected type */ /* {...baby, job: job}; */ { name: baby.name, age: baby.age, job: job, }; }; ``` -------------------------------- ### Functions with No Arguments (Unit) in ReasonML Source: https://reasonml.github.io/docs/en/function Illustrates how to define functions that take no arguments using the 'unit' type represented by '()'. This pattern is often used for functions with side effects. The example shows defining and calling such a function. ```reasonml let launchMissile = () => { someSideEffects(); print_endline("Missiles have been launched!"); }; launchMissile(); ``` -------------------------------- ### ReasonML Array to List Conversion Source: https://reasonml.github.io/docs/en/basic-structures Demonstrates converting between ReasonML arrays and lists using `Array.to_list` and `Array.of_list`. This is useful for leveraging the strengths of both data structures. ```reasonml let list = Array.to_list(array); let array = Array.of_list(list); ``` -------------------------------- ### ReasonML List Creation and Concatenation Source: https://reasonml.github.io/docs/en/basic-structures Demonstrates how to create immutable lists in ReasonML and concatenate them using the spread operator and the '@' operator. It also shows the correct way to add elements to the front of a list. ```reasonml let listA = [1, 2, 3]; let listB = [0, ...listA]; let listC = [-1, 0, ...listA]; let listD = listA @ listB @ [7, 8]; ``` -------------------------------- ### Declare and Concatenate Strings in ReasonML Source: https://reasonml.github.io/docs/en/primitives Demonstrates how to declare strings using double quotes and concatenate them using the '++' operator in ReasonML. It also shows examples of using standard library functions for string manipulation. ```reasonml let s = "Hello World!"; ``` ```reasonml let s = "Hello " ++ "World!"; ``` ```reasonml let s = String.trim(" extra whitespace\n"); /* "extra whitespace" */ let s = String.concat("\n", ["line 1", "line 2"]); /* "Line 1\nLine 2" */ let s = String.sub("Hello World!", 6, 5); /* "World" */ ``` -------------------------------- ### ReasonML Block Scope Demonstration Source: https://reasonml.github.io/docs/en/let-binding Explains and demonstrates block scoping in ReasonML using curly braces `{}`. Bindings declared within a block are only accessible within that block, and the last expression in the block is implicitly returned. ```reasonml let message = { let part1 = "hello"; let part2 = "world"; part1 ++ " " ++ part2 }; /* `part1` and `part2` not accessible here! */ ``` -------------------------------- ### ReasonML Tuple Pattern Matching Source: https://reasonml.github.io/docs/en/basic-structures Demonstrates using pattern matching to deconstruct tuples in ReasonML. This allows for conditional logic based on the values within the tuple. ```reasonml switch (pair) { | ("hello", name) => print_endline("Hello " ++ name); | ("bye", name) => print_endline("Goodbye " ++ name); | (command, _) => print_endline("Unknown command: " ++ command); }; ``` -------------------------------- ### ReasonML Exhaustive Pattern Matching Warning Source: https://reasonml.github.io/docs/en/pattern-matching Demonstrates ReasonML's exhaustive pattern matching warning, which alerts developers when not all possible values of an input are covered in a switch statement. Includes examples of both non-exhaustive and exhaustive patterns, and the use of `_` for unmatched cases. ```reasonml let f = x => switch (x) { /* Warning: this pattern-matching is not exhaustive. */ | 0 => "zero" }; f(2); /* Exception: Match_failure */ ``` ```reasonml switch (x) { | 0 => "zero" | _ => "another number" }; ``` ```reasonml type t = | A(string, int) | B(string, (int, int)) | C(list(point)); let x = A("hi", 2); switch (x) { | A("a", _) => 0 | A(_) => 1 | B(_, (i, _)) => i | C([{x, y}, ..._]) => x + y | _ => 2 } ``` ```reasonml switch (x) { | A("a", _) => 0 | A(_) => 1 | B(_, (i, _)) => i | C([{x, y}, ..._]) => x + y | C([]) => 2 } ``` -------------------------------- ### Defining and Using a Two-Parameter Type in ReasonML Source: https://reasonml.github.io/docs/en/type Illustrates the definition and usage of a parameterized type in ReasonML that accepts multiple type parameters. The 'pair' type takes two parameters, 'a and 'b, and is shown with examples of int/string and string/list(int) combinations. ```reasonml type pair('a, 'b) = ('a, 'b); let x: pair(int, string) = (1, "one"); let y: pair(string, list(int)) = ("123", [1, 2, 3]); ``` -------------------------------- ### Non-Mandatory Named Arguments in ReasonML Source: https://reasonml.github.io/docs/en/function Details how to define named arguments that are not required at call time using '=?' and how to provide default values using '=value'. The example shows handling optional arguments with and without default values, including the use of 'switch' with 'option'. ```reasonml let addOne = (~value=?, ()) => { switch (value) { | Some(value) => value + 1 | None => 1 }; }; addOne(); /* 1 */ addOne(~value=11, ()); /* 12 */ ``` ```reasonml let makeCircle = (~x=0, ~y=0, ~radius=10, ()) => { ... }; /* Position (0, 0) with radius 10 */ makeCircle(); /* Position (10, 0) with radius 2 */ makeCircle(~x=10, ~radius=2, ()); ``` -------------------------------- ### Partial Application of Functions in ReasonML Source: https://reasonml.github.io/docs/en/function Illustrates partial application, where a function is called with some arguments, returning a new function that expects the remaining arguments. This is shown for both first and non-first arguments using the '_' placeholder. ```reasonml let add = (x, y) => x + y; let addFive = add(5); let eleven = addFive(6); let twelve = addFive(7); ``` ```reasonml let divide = (a, b) => a / b; let half = divide(_, 2); let five = half(10); ``` -------------------------------- ### Named Arguments in ReasonML Functions Source: https://reasonml.github.io/docs/en/function Explains the use of named arguments in ReasonML functions, denoted by a '~' prefix. This improves readability, especially with multiple arguments or arguments of the same type. The example shows defining and calling functions with named arguments, including changing the calling order. ```reasonml let makeCircle = (~x, ~y, ~radius) => { ... }; ``` ```reasonml makeCircle(~x=5, ~y=5, ~radius=10); ``` ```reasonml makeCircle(~radius=10, ~y=5, ~x=5); ``` -------------------------------- ### Open a ReasonML Module to Access Members Directly Source: https://reasonml.github.io/docs/en/module Shows how to use the `open` keyword to make all members of a module directly accessible in the current scope without prefixing the module name. Use `open` sparingly to avoid namespace pollution. ```reasonml open Duration; let fiveSeconds = fromSeconds(5); let tenSeconds = add(fiveSeconds, fiveSeconds); ``` -------------------------------- ### Reason Language Capabilities and Comparisons Source: https://reasonml.github.io/docs/en/faq This section outlines the capabilities of the Reason language, drawing parallels to JavaScript and OCaml. It highlights Reason's ability to compile to type-safe JavaScript using the Melange compiler, its performance for native CLI applications, and its declarative UI framework, revery-ui, which uses a ReactJS-like paradigm with JSX. It also contrasts Reason with languages like Rust and Go, emphasizing its garbage collection and lack of borrow-checking. ```reason (* Example of using revery-ui with JSX-like syntax *) let component = { @react.component let make = (~name: string) => {
{React.string("Hello " ++ name ++ "!")}
}; }; ``` -------------------------------- ### ReasonML Array Pattern Matching Source: https://reasonml.github.io/docs/en/basic-structures Illustrates pattern matching with arrays in ReasonML. Unlike lists, arrays do not support the `...rest` syntax in pattern matching. ```reasonml switch (array) { | [||] => "empty" | [| first |] => "exactly one" | [| first, second |] => "exactly two" | _ => "at least three" }; ``` -------------------------------- ### Define Basic Named Functions in ReasonML Source: https://reasonml.github.io/docs/en/function Demonstrates how to define named functions using 'let' bindings, parentheses for arguments, and an arrow '=>'. It shows both block-style and concise function bodies, as well as how to call these functions. ```reasonml let add = (x, y) => { x + y; }; ``` ```reasonml let add = (x, y) => x + y; ``` ```reasonml let twentyThree = add(10, 13); ``` -------------------------------- ### Handle Options for Optional Arguments in ReasonML Source: https://reasonml.github.io/docs/en/function Demonstrates how to pass `Some(data)` or `None` to optional named arguments. It shows the incorrect direct passing of an option and the correct way using a switch statement and the '?' shorthand for concise handling. ```reasonml let fn = (~data=?, ()) => { ... }; let x = Some(100); /* Provide data based on whether x is Some or None */ switch (x) { | Some(data) => fn(~data, ()); | None => fn(); }; /* Error: Incorrect type */ fn(~data=x, ()); let a = Some(100); let b = None; /* fn is called like `fn(~data=100, ())` */ fn(~data=?a, ()); /* fn is called like `fn()` */ fn(~data=?b, ()); ``` -------------------------------- ### Pattern Matching on Variants - ReasonML Source: https://reasonml.github.io/docs/en/variant Illustrates how to use pattern matching with a 'switch' statement to handle different cases of the 'animal' variant. It maps each animal type to a specific interaction string, ensuring all cases are covered. ```reasonml let interact = (animal) => { switch (animal) { | Cat => "pet" | Dog => "throw ball" | Horse => "ride" | Snake => "run away" }; }; ``` -------------------------------- ### ReasonML Array Mapping and Folding Source: https://reasonml.github.io/docs/en/basic-structures Illustrates mapping over an array to transform its elements and folding an array to reduce it to a single value using `Array.map` and `Array.fold_left`. ```reasonml let doubled = Array.map(i => i * 2, array); let max = Array.fold_left( (result, item) => item > result ? item : result, initialValue, array, ); ```