Skip to content

Commit db785db

Browse files
authored
Merge pull request #319 from kevanstannard/syntax-lookup-switch
Syntax lookup: Switch
2 parents ae5d3a8 + a389689 commit db785db

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

misc_docs/syntax/language_switch.mdx

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
---
2+
id: "switch"
3+
keywords: ["switch", "pattern", "match"]
4+
name: "switch"
5+
summary: "This is the `switch` expression keyword."
6+
category: "languageconstructs"
7+
---
8+
9+
A `switch` expression allows you to match / destructure almost any kind of value (array, list, records, strings, numbers, variants, etc). Each branch (pattern) of a `switch` expression must return a value of the same type.
10+
11+
### Example
12+
13+
<CodeTab labels={["ReScript", "JS Output"]}>
14+
15+
```res
16+
type shape = Circle(float) | Square(float)
17+
18+
let shape = Square(3.0)
19+
20+
let message = switch shape {
21+
| Circle(radius) => "Circle with radius " ++ Js.Float.toString(radius)
22+
| Square(length) => "Square with sides of length " ++ Js.Float.toString(length)
23+
}
24+
```
25+
26+
```js
27+
var shape = {
28+
TAG: /* Square */ 1,
29+
_0: 3.0,
30+
};
31+
32+
var message;
33+
34+
message =
35+
shape.TAG === /* Circle */ 0
36+
? "Circle with radius " + (3.0).toString()
37+
: "Square with sides of length " + (3.0).toString();
38+
```
39+
40+
</CodeTab>
41+
42+
43+
### References
44+
45+
* [Switch Based on Shape of Data](/docs/manual/latest/pattern-matching-destructuring#switch-based-on-shape-of-data)

0 commit comments

Comments
 (0)