|
| 1 | +# Belt |
| 2 | + |
| 3 | +The ReScript standard library. |
| 4 | + |
| 5 | +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. |
| 6 | + |
| 7 | +## Motivation |
| 8 | + |
| 9 | +Belt provides: |
| 10 | + |
| 11 | +- The **highest quality** immutable data structures in JavaScript. |
| 12 | +- Safety by default: A Belt function will never throw exceptions, unless it is |
| 13 | + indicated explicitly in the function name (suffix "Exn"). |
| 14 | +- Better performance and smaller code size running on the JS platform. |
| 15 | +- Ready for [Tree Shaking](https://webpack.js.org/guides/tree-shaking/). |
| 16 | + |
| 17 | +## Usage |
| 18 | + |
| 19 | +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 |
| 20 | + |
| 21 | +```res |
| 22 | +open Belt |
| 23 | +``` |
| 24 | + |
| 25 | +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. |
| 26 | + |
| 27 | +If you want to open Belt globally for all files in your project instead, you can put |
| 28 | + |
| 29 | +```json |
| 30 | + "bsc-flags": ["-open Belt"], |
| 31 | +``` |
| 32 | + |
| 33 | +into your `bsconfig.json`. |
| 34 | + |
| 35 | +**Note**: this is the **only** `open` we encourage. |
| 36 | + |
| 37 | +Example usage: |
| 38 | + |
| 39 | +```res |
| 40 | +let someNumbers = [1, 1, 4, 2, 3, 6, 3, 4, 2] |
| 41 | +
|
| 42 | +let greaterThan2UniqueAndSorted = |
| 43 | + someNumbers |
| 44 | + ->Belt.Array.keep(x => x > 2) |
| 45 | + // convert to and from set to make values unique |
| 46 | + ->Belt.Set.Int.fromArray |
| 47 | + ->Belt.Set.Int.toArray // output is already sorted |
| 48 | +
|
| 49 | +Js.log2("result", greaterThan2UniqueAndSorted) |
| 50 | +``` |
| 51 | + |
| 52 | +## Curried vs. Uncurried Callbacks |
| 53 | + |
| 54 | +For functions taking a callback parameter, there are usually two versions |
| 55 | +available: |
| 56 | + |
| 57 | +- curried (no suffix) |
| 58 | +- uncurried (suffixed with `U`) |
| 59 | + |
| 60 | +E.g.: |
| 61 | + |
| 62 | +```res |
| 63 | +let forEach: (t<'a>, 'a => unit) => unit |
| 64 | +
|
| 65 | +let forEachU: (t<'a>, (. 'a) => unit) => unit |
| 66 | +``` |
| 67 | + |
| 68 | +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. |
| 69 | + |
| 70 | +The two versions can be invoked as follows: |
| 71 | + |
| 72 | +``` |
| 73 | +["a", "b", "c"]->Belt.Array.forEach(x => Js.log(x)) |
| 74 | +
|
| 75 | +["a", "b", "c"]->Belt.Array.forEachU((. x) => Js.log(x)) |
| 76 | +``` |
| 77 | + |
| 78 | +## Specialized Collections |
| 79 | + |
| 80 | +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. |
| 81 | + |
| 82 | +For example, Belt has the following set modules: |
| 83 | + |
| 84 | +- [Belt.Set](belt/set) |
| 85 | +- [Belt.Set.Int](belt/set-int) |
| 86 | +- [Belt.Set.String](belt/set-string) |
| 87 | + |
| 88 | +## Implementation Details |
| 89 | + |
| 90 | +### Array access runtime safety |
| 91 | + |
| 92 | +One common confusion comes from the way Belt handles array access. It differs from than the default standard library's. |
| 93 | + |
| 94 | +```res |
| 95 | +let letters = ["a", "b", "c"] |
| 96 | +let a = letters[0] // a == "a" |
| 97 | +let capitalA = Js.String.toUpperCase(a) |
| 98 | +let k = letters[10] // Raises an exception! The 10th index doesn't exist. |
| 99 | +``` |
| 100 | + |
| 101 | +Because Belt avoids exceptions and returns `options` instead, this code behaves differently: |
| 102 | + |
| 103 | +```res |
| 104 | +open Belt |
| 105 | +let letters = ["a", "b", "c"] |
| 106 | +let a = letters[0] // a == Some("a") |
| 107 | +let captialA = Js.String.toUpperCase(a) // Type error! This code will not compile. |
| 108 | +let k = letters[10] // k == None |
| 109 | +``` |
| 110 | + |
| 111 | +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: |
| 112 | + |
| 113 | +- Reason transforms array index access to the function `Array.get`. So `letters[0]` is the same as `Array.get(letters, 0)`. |
| 114 | +- The compiler uses whichever `Array` module is in scope. If you `open Belt`, then it uses `Belt.Array`. |
| 115 | +- `Belt.Array.get` returns values wrapped in options, so `letters[0] == Some("a")`. |
| 116 | + |
| 117 | +Fortunately, this is easy to fix: |
| 118 | + |
| 119 | +```res example |
| 120 | +open Belt |
| 121 | +let letters = ["a", "b", "c"] |
| 122 | +let a = letters[0] |
| 123 | +
|
| 124 | +// Use a switch statement: |
| 125 | +let capitalA = |
| 126 | + switch a { |
| 127 | + | Some(a) => Some(Js.String.toUpperCase(a)) |
| 128 | + | None => None |
| 129 | + } |
| 130 | +
|
| 131 | +let k = letters[10] // k == None |
| 132 | +``` |
| 133 | + |
| 134 | +With that little bit of tweaking, our code now compiles successfully and is 100% free of runtime errors! |
| 135 | + |
| 136 | +### A Special Encoding for Collection Safety |
| 137 | + |
| 138 | +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. |
| 139 | + |
| 140 | +We use a phantom type to solve the problem: |
| 141 | + |
| 142 | +```res |
| 143 | +module Comparable1 = |
| 144 | + Belt.Id.MakeComparable( |
| 145 | + { |
| 146 | + type t = (int, int) |
| 147 | + let cmp = ((a0, a1), (b0, b1)) => |
| 148 | + switch Pervasives.compare(a0, b0) { |
| 149 | + | 0 => Pervasives.compare(a1, b1) |
| 150 | + | c => c |
| 151 | + } |
| 152 | + } |
| 153 | + ) |
| 154 | +
|
| 155 | +let mySet1 = Belt.Set.make(~id=module(Comparable1)) |
| 156 | +
|
| 157 | +module Comparable2 = |
| 158 | + Belt.Id.MakeComparable( |
| 159 | + { |
| 160 | + type t = (int, int) |
| 161 | + let cmp = ((a0, a1), (b0, b1)) => |
| 162 | + switch Pervasives.compare(a0, b0) { |
| 163 | + | 0 => Pervasives.compare(a1, b1) |
| 164 | + | c => c |
| 165 | + } |
| 166 | + } |
| 167 | + ) |
| 168 | +
|
| 169 | +let mySet2 = Belt.Set.make(~id=module(Comparable2)) |
| 170 | +``` |
| 171 | + |
| 172 | +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. |
| 173 | + |
| 174 | +```res |
| 175 | +let mySet1: t<(int, int), Comparable1.identity> |
| 176 | +let mySet2: t<(int, int), Comparable2.identity> |
| 177 | +``` |
| 178 | + |
| 179 | +`Comparable1.identity` and `Comparable2.identity` are not the same using our encoding scheme. |
0 commit comments