@@ -356,3 +356,61 @@ The compiler sees the variant, then
356
356
357
357
1 . conceptually turns them into ` type animal = 0 | 1 | 2 `
358
358
2 . compiles ` switch ` to a constant-time jump table (` O(1) ` ).
359
+
360
+ ## Extensible Variant Types
361
+
362
+ Variants can be made extensible by defining a type using ` .. ` and adding new variant constructors using ` += ` .
363
+
364
+ <CodeTab labels = { [" ReScript" , " JS Output" ]} >
365
+
366
+ ``` res example
367
+ type t = ..
368
+
369
+ type t += Other
370
+
371
+ type t +=
372
+ | Point(float, float)
373
+ | Line(float, float, float, float)
374
+ ```
375
+ ``` js
376
+ var Caml_exceptions = require (" ./stdlib/caml_exceptions.js" );
377
+
378
+ var Other = Caml_exceptions .create (" Playground.Other" );
379
+
380
+ var Point = Caml_exceptions .create (" Playground.Point" );
381
+
382
+ var Line = Caml_exceptions .create (" Playground.Line" );
383
+ ```
384
+
385
+ </CodeTab >
386
+
387
+ Pattern-matching is possible the same way as with normal variants but there is one caveat:
388
+ With extensible variants, the possibility to check for exhaustiveness vanishes, you always need a default case ` _ ` here.
389
+
390
+
391
+ <CodeTab labels = { [" ReScript" , " JS Output" ]} >
392
+
393
+
394
+ ``` res example
395
+ let print = v =>
396
+ switch v {
397
+ | Point(x, y) => Js.log2("Point", (x, y))
398
+ | Line(ax, ay, bx, by) => Js.log2("Line", (ax, ay, bx, by))
399
+ | Other
400
+ | _ =>
401
+ Js.log("Other")
402
+ }
403
+ ```
404
+ ``` js
405
+ function print (v ) {
406
+ if (v .RE_EXN_ID === Point ) {
407
+ console .log (" Point" , [v ._1 , v ._2 ]);
408
+ } else if (v .RE_EXN_ID === Line) {
409
+ console .log (" Line" , [v ._1 , v ._2 , v ._3 , v ._4 ]);
410
+ } else {
411
+ console .log (" Other" );
412
+ }
413
+ }
414
+ ```
415
+
416
+ </CodeTab >
0 commit comments