|
1 | 1 | --- |
2 | 2 | title: "Dictionary" |
3 | | -description: "Dictionary type from ReScript Core" |
| 3 | +description: "Dictionary data structure in ReScript" |
4 | 4 | canonical: "/docs/manual/v12.0.0/dict" |
5 | 5 | --- |
6 | 6 |
|
7 | 7 | # Dictionary |
8 | 8 |
|
9 | | -A mutable dictionary with string keys. |
10 | | -Compiles to a regular JavaScript object. |
11 | | -Defined in the [Core](/docs/manual/v12.0.0/api/core/dict). |
| 9 | +ReScript has first class support for dictionaries. Dictionaries are mutable objects with string keys, where all values must have the same type. Dicts compile to regular JavaScript objects at runtime. |
12 | 10 |
|
13 | 11 | ## Create |
14 | 12 |
|
15 | | -We have a dedicated syntax to create a new Dictionary. |
| 13 | +You can create a new dictionary in a few different ways, depending on your use case. |
16 | 14 |
|
17 | 15 | <CodeTab labels={["ReScript", "JS Output"]}> |
18 | 16 |
|
19 | 17 | ```res prelude |
| 18 | +// Using the first class dict syntax |
20 | 19 | let d = dict{"A": 5, "B": 6} |
| 20 | +
|
| 21 | +// Programatically via the standard library |
| 22 | +let d2 = Dict.fromArray([("A", 5), ("B", 6)]) |
21 | 23 | ``` |
22 | 24 |
|
23 | 25 | ```js |
24 | 26 | let d = { |
25 | 27 | A: 5, |
26 | 28 | B: 6 |
27 | 29 | }; |
28 | | -``` |
29 | | - |
30 | | -</CodeTab> |
31 | 30 |
|
32 | | -⚠️ The keys of a dictionary are always strings and the values all have the same type. |
33 | | -You will get a compiler error if this is not the case! |
| 31 | +let d2 = Object.fromEntries([ |
| 32 | + [ |
| 33 | + "A", |
| 34 | + 5 |
| 35 | + ], |
| 36 | + [ |
| 37 | + "B", |
| 38 | + 6 |
| 39 | + ] |
| 40 | +]); |
34 | 41 |
|
35 | | -<CodeTab labels={["ReScript", "JS Output"]}> |
36 | | - |
37 | | -```res prelude |
38 | | -let d = dict{"A": 5, "B": "Hej"} |
39 | 42 | ``` |
40 | 43 |
|
41 | | -```js |
42 | | -We've found a bug for you! |
43 | | -
|
44 | | - 1 │ let d = dict{"A": 5, "B": "Hej"} |
| 44 | +</CodeTab> |
45 | 45 |
|
46 | | - This has type: string |
47 | | - But it's expected to have type: int |
48 | | - |
49 | | - You can convert string to int with Int.fromString. |
50 | | -``` |
| 46 | +A few things to note here: |
51 | 47 |
|
52 | | -</CodeTab> |
| 48 | +* Using the first class `dict{}` syntax compiles cleanly to a JavaScript object directly |
| 49 | +* Using `Dict.fromArray` is useful when you need to create a dictionary programatically |
53 | 50 |
|
54 | 51 | ## Access |
55 | 52 |
|
56 | | -You can access values from a Dictionary either via the the Core module functions, |
57 | | -or using pattern matching. |
| 53 | +You can access values from a Dictionary either via the the standard library `Dict` module functions, or using pattern matching. |
58 | 54 |
|
59 | 55 | <CodeTab labels={["ReScript", "JS Output"]}> |
60 | 56 |
|
61 | 57 | ```res prelude |
62 | | -let d = dict{"A": 5, "B": 6} |
63 | | -let a : option<int> = d->Dict.get("A") |
| 58 | +let d = dict{"A": 5, "B": 6, "C": 7} |
| 59 | +
|
| 60 | +// Using `Dict.get` |
| 61 | +let a = d->Dict.get("A") |
64 | 62 |
|
| 63 | +// Switching on the full dict |
65 | 64 | let b = switch d { |
66 | 65 | | dict{"B": b} => Some(b) |
67 | 66 | | _ => None |
68 | 67 | } |
| 68 | +
|
| 69 | +// Destructuring |
| 70 | +let dict{"C": ?c} = d |
69 | 71 | ``` |
70 | 72 |
|
71 | 73 | ```js |
72 | 74 | let d = { |
73 | 75 | A: 5, |
74 | | - B: 6 |
| 76 | + B: 6, |
| 77 | + C: 7 |
75 | 78 | }; |
76 | 79 |
|
77 | 80 | let a = d["A"]; |
78 | 81 |
|
79 | 82 | let b = d.B; |
80 | 83 |
|
81 | 84 | let b$1 = b !== undefined ? b : undefined; |
82 | | -``` |
83 | 85 |
|
| 86 | +let c = d.C; |
| 87 | +``` |
84 | 88 | </CodeTab> |
85 | 89 |
|
86 | | -### Pattern match with JSON.t |
| 90 | +> In the Destructuring example, we're using the `?` optional pattern match syntax to pull out the `C` key value as an optional, regardless of if the dict has it or not. |
| 91 | +
|
| 92 | +## Pattern matching |
| 93 | +Dictionaries have first class support for pattern matching. Read more in the [dedicated guide on pattern matching and destructring in ReScript](pattern-matching-destructuring.md#match-on-dictionaries). |
87 | 94 |
|
88 | | -Pattern matching a Dictionary with the `dict{}` can be very elegant if you received an (external) [JSON.t](/docs/manual/v12.0.0/api/core/json) object. |
| 95 | +## Updating and setting values |
| 96 | + |
| 97 | +You can set and update new values on your dictionary using the `Dict.set` function. All updates are mutable. |
89 | 98 |
|
90 | 99 | <CodeTab labels={["ReScript", "JS Output"]}> |
91 | 100 |
|
92 | 101 | ```res prelude |
93 | | -@module("some-module") |
94 | | -external getSettings: string => JSON.t = "getSettings" |
95 | | -
|
96 | | -let vapidKey = switch getSettings("user") { |
97 | | -| JSON.Object(dict{ |
98 | | - "notifications": // A nested object structure |
99 | | - JSON.Object(dict{"vapidKey": JSON.String(key)}), |
100 | | - }) => |
101 | | - Some(key) |
102 | | -| _ => { |
103 | | - Console.log("key not found") |
104 | | - None |
105 | | - } |
106 | | -} |
| 102 | +let d = dict{"A": 5, "B": 6} |
| 103 | +
|
| 104 | +d->Dict.set("C", 7) |
107 | 105 | ``` |
108 | 106 |
|
109 | 107 | ```js |
110 | | -import * as SomeModule from "some-module"; |
111 | | - |
112 | | -let match = SomeModule.getSettings("user"); |
113 | | - |
114 | | -let vapidKey; |
115 | | - |
116 | | -if (typeof match === "object" && match !== null && !Array.isArray(match)) { |
117 | | - let match$1 = match.notifications; |
118 | | - if (typeof match$1 === "object" && match$1 !== null && !Array.isArray(match$1)) { |
119 | | - let key = match$1.vapidKey; |
120 | | - if (typeof key === "string") { |
121 | | - vapidKey = key; |
122 | | - } else { |
123 | | - console.log("key not found"); |
124 | | - vapidKey = undefined; |
125 | | - } |
126 | | - } else { |
127 | | - console.log("key not found"); |
128 | | - vapidKey = undefined; |
129 | | - } |
130 | | -} else { |
131 | | - console.log("key not found"); |
132 | | - vapidKey = undefined; |
133 | | -} |
| 108 | +let d = { |
| 109 | + A: 5, |
| 110 | + B: 6 |
| 111 | +}; |
| 112 | + |
| 113 | +d["C"] = 7; |
134 | 114 | ``` |
135 | 115 |
|
136 | 116 | </CodeTab> |
137 | 117 |
|
138 | | -## Mutable Update |
| 118 | +## Advanced example: Pattern matching on JSON |
139 | 119 |
|
140 | | -Updating an entry happens via the `Dict.set` function. |
| 120 | +JSON objects are represented as dictionaries (`dict<JSON.t>`). You can leverage that fact to decode JSON in a nice way, using only language features: |
141 | 121 |
|
142 | 122 | <CodeTab labels={["ReScript", "JS Output"]}> |
143 | 123 |
|
144 | 124 | ```res prelude |
145 | | -let d = dict{"A": 5, "B": 6} |
146 | | -let a : option<int> = d->Dict.get("A") |
| 125 | +type user = { |
| 126 | + name: string, |
| 127 | + email: string, |
| 128 | +} |
147 | 129 |
|
148 | | -let b = switch d { |
149 | | -| dict{"B": b} => Some(b) |
150 | | -| _ => None |
| 130 | +/** Decode JSON to a `user`. |
| 131 | +let decodeUser = (json: JSON.t) => { |
| 132 | + switch json { |
| 133 | + | Object(dict{"name": JSON.String(name), "email": JSON.String(email)}) => |
| 134 | + Some({name, email}) |
| 135 | + | _ => None |
| 136 | + } |
151 | 137 | } |
| 138 | +
|
152 | 139 | ``` |
153 | 140 |
|
154 | 141 | ```js |
155 | | -let d = { |
156 | | - A: 5, |
157 | | - B: 6 |
158 | | -}; |
159 | | - |
160 | | -d["A"] = -1; |
161 | | - |
162 | | -d["C"] = 0; |
| 142 | +function decodeUser(json) { |
| 143 | + if (typeof json !== "object" || json === null || Array.isArray(json)) { |
| 144 | + return; |
| 145 | + } |
| 146 | + let name = json.name; |
| 147 | + if (typeof name !== "string") { |
| 148 | + return; |
| 149 | + } |
| 150 | + let email = json.email; |
| 151 | + if (typeof email === "string") { |
| 152 | + return { |
| 153 | + name: name, |
| 154 | + email: email |
| 155 | + }; |
| 156 | + } |
| 157 | + |
| 158 | +} |
163 | 159 | ``` |
164 | 160 |
|
165 | | -</CodeTab> |
| 161 | +</CodeTab> |
0 commit comments