Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions data/sidebar_manual_v1000.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
{
"Overview": [
"introduction",
"installation",
"editor-plugins",
"migrate-from-bucklescript-reason",
"try"
],
"Language Features": [
"overview",
"let-binding",
"type",
"primitive-types",
"tuple",
"record",
"object",
"variant",
"polymorphic-variant",
"null-undefined-option",
"array-and-list",
"function",
"control-flow",
"pipe",
"pattern-matching-destructuring",
"mutation",
"jsx",
"exception",
"lazy-values",
"promise",
"async-await",
"module",
"import-export",
"attribute",
"unboxed",
"reserved-keywords"
],
"Advanced Features": [
"extensible-variant",
"scoped-polymorphic-types"
],
"JavaScript Interop": [
"interop-cheatsheet",
"embed-raw-javascript",
"shared-data-types",
"external",
"bind-to-js-object",
"bind-to-js-function",
"import-from-export-to-js",
"bind-to-global-js-values",
"json",
"inlining-constants",
"use-illegal-identifier-names",
"generate-converters-accessors",
"browser-support-polyfills",
"libraries"
],
"Build System": [
"build-overview",
"build-configuration",
"build-configuration-schema",
"build-external-stdlib",
"build-pinned-dependencies",
"interop-with-js-build-systems",
"build-performance",
"warning-numbers"
],
"Guides": [
"converting-from-js"
],
"Extra": [
"newcomer-examples",
"project-structure",
"faq"
]
}
15 changes: 15 additions & 0 deletions pages/docs/manual/v10.0.0/api.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Overview

ReScript ships 3 modules in its standard library.

- [Js](api/js): bindings for all your familiar JavaScript APIs.
- [Belt](api/belt): extra collections and helpers not available in JavaScript.
- [Dom](api/dom): Dom related types and modules.

Usage heuristics:

- Default to using the `Js` module. Most of the APIs in it are runtime-free and compile down to clean, readable JavaScript, which is our priority.
- For other APIs that aren't available in regular JavaScript (and thus don't exist in our `Js` bindings), use Belt. For example, prefer `Js.Array2` over `Belt.Array`.
- The `Dom` module contains our standardized types used by various userland DOM bindings. Due to the complexity of DOM, we don't mind that you ignore this module and build your application-specific DOM bindings.

**Note**: we do not recommend other userland standard library alternatives (unless it's DOM bindings). These cause confusion and split points for the community.
179 changes: 179 additions & 0 deletions pages/docs/manual/v10.0.0/api/belt.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
# Belt

The ReScript standard library.

Belt is currently mostly covering collection types. It has no string or date functions yet, although Belt.String is in the works. In the meantime, use [Js.String](js/string) for string functions and [Js.Date](js/date) for date functions.

## Motivation

Belt provides:

- The **highest quality** immutable data structures in JavaScript.
- Safety by default: A Belt function will never throw exceptions, unless it is
indicated explicitly in the function name (suffix "Exn").
- Better performance and smaller code size running on the JS platform.
- Ready for [Tree Shaking](https://webpack.js.org/guides/tree-shaking/).

## Usage

To use modules from Belt, either refer to them by their fully qualified name (`Belt.List`, `Belt.Array` etc.) or open the `Belt` module by putting

```res
open Belt
```

at the top of your source files. After opening Belt this way, `Array` will refer to `Belt.Array`, `List` will refer to `Belt.List` etc. in the subsequent code.

If you want to open Belt globally for all files in your project instead, you can put

```json
"bsc-flags": ["-open Belt"],
```

into your `bsconfig.json`.

**Note**: this is the **only** `open` we encourage.

Example usage:

```res
let someNumbers = [1, 1, 4, 2, 3, 6, 3, 4, 2]

let greaterThan2UniqueAndSorted =
someNumbers
->Belt.Array.keep(x => x > 2)
// convert to and from set to make values unique
->Belt.Set.Int.fromArray
->Belt.Set.Int.toArray // output is already sorted

Js.log2("result", greaterThan2UniqueAndSorted)
```

## Curried vs. Uncurried Callbacks

For functions taking a callback parameter, there are usually two versions
available:

- curried (no suffix)
- uncurried (suffixed with `U`)

E.g.:

```res
let forEach: (t<'a>, 'a => unit) => unit

let forEachU: (t<'a>, (. 'a) => unit) => unit
```

The uncurried version will be faster in some cases, but for simplicity we recommend to stick with the curried version unless you need the extra performance.

The two versions can be invoked as follows:

```
["a", "b", "c"]->Belt.Array.forEach(x => Js.log(x))

["a", "b", "c"]->Belt.Array.forEachU((. x) => Js.log(x))
```

## Specialized Collections

For collections types like set or map, Belt provides both a generic module as well as specialized, more efficient implementations for string and int keys.

For example, Belt has the following set modules:

- [Belt.Set](belt/set)
- [Belt.Set.Int](belt/set-int)
- [Belt.Set.String](belt/set-string)

## Implementation Details

### Array access runtime safety

One common confusion comes from the way Belt handles array access. It differs from than the default standard library's.

```res
let letters = ["a", "b", "c"]
let a = letters[0] // a == "a"
let capitalA = Js.String.toUpperCase(a)
let k = letters[10] // Raises an exception! The 10th index doesn't exist.
```

Because Belt avoids exceptions and returns `options` instead, this code behaves differently:

```res
open Belt
let letters = ["a", "b", "c"]
let a = letters[0] // a == Some("a")
let captialA = Js.String.toUpperCase(a) // Type error! This code will not compile.
let k = letters[10] // k == None
```

Although we've fixed the problem where `k` raises an exception, we now have a type error when trying to capitalize `a`. There are a few things going on here:

- Reason transforms array index access to the function `Array.get`. So `letters[0]` is the same as `Array.get(letters, 0)`.
- The compiler uses whichever `Array` module is in scope. If you `open Belt`, then it uses `Belt.Array`.
- `Belt.Array.get` returns values wrapped in options, so `letters[0] == Some("a")`.

Fortunately, this is easy to fix:

```res example
open Belt
let letters = ["a", "b", "c"]
let a = letters[0]

// Use a switch statement:
let capitalA =
switch a {
| Some(a) => Some(Js.String.toUpperCase(a))
| None => None
}

let k = letters[10] // k == None
```

With that little bit of tweaking, our code now compiles successfully and is 100% free of runtime errors!

### A Special Encoding for Collection Safety

When we create a collection library for a custom data type we need a way to provide a comparator function. Take Set for example, suppose its element type is a pair of ints, it needs a custom compare function that takes two tuples and returns their order. The Set could not just be typed as Set.t (int \* int) , its customized compare function needs to manifest itself in the signature, otherwise, if the user creates another customized compare function, the two collection could mix which would result in runtime error.

We use a phantom type to solve the problem:

```res
module Comparable1 =
Belt.Id.MakeComparable(
{
type t = (int, int)
let cmp = ((a0, a1), (b0, b1)) =>
switch Pervasives.compare(a0, b0) {
| 0 => Pervasives.compare(a1, b1)
| c => c
}
}
)

let mySet1 = Belt.Set.make(~id=module(Comparable1))

module Comparable2 =
Belt.Id.MakeComparable(
{
type t = (int, int)
let cmp = ((a0, a1), (b0, b1)) =>
switch Pervasives.compare(a0, b0) {
| 0 => Pervasives.compare(a1, b1)
| c => c
}
}
)

let mySet2 = Belt.Set.make(~id=module(Comparable2))
```

Here, the compiler would infer `mySet1` and `mySet2` having different type, so e.g. a `merge` operation that tries to merge these two sets will correctly fail.

```res
let mySet1: t<(int, int), Comparable1.identity>
let mySet2: t<(int, int), Comparable2.identity>
```

`Comparable1.identity` and `Comparable2.identity` are not the same using our encoding scheme.
Loading