Skip to content

Commit fc813fd

Browse files
committed
Add tagged unions example from chatgpt.
1 parent e1adb1a commit fc813fd

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

jscomp/test/variantsMatching.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,23 @@ var MyNullableExtended = {
345345
expectSeven: expectSeven$1
346346
};
347347

348+
function area(shape) {
349+
switch (shape.TAG) {
350+
case "Circle" :
351+
return Math.PI * Math.pow(shape._0.radius, 2);
352+
case "Square" :
353+
return Math.pow(shape._0.sideLength, 2);
354+
case "Rectangle" :
355+
var match = shape._0;
356+
return match.width * match.height;
357+
358+
}
359+
}
360+
361+
var TaggedUnions = {
362+
area: area
363+
};
364+
348365
exports.toEnum = toEnum;
349366
exports.toString = toString;
350367
exports.bar = bar;
@@ -360,4 +377,5 @@ exports.MyUndefined = MyUndefined;
360377
exports.MyNull = MyNull;
361378
exports.MyNullable = MyNullable;
362379
exports.MyNullableExtended = MyNullableExtended;
380+
exports.TaggedUnions = TaggedUnions;
363381
/* expectSeven Not a pure module */

jscomp/test/variantsMatching.res

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,3 +204,65 @@ module MyNullableExtended = {
204204
let expectSeven = plus(Present({x: 4., y: 3.}), Present({x: 3., y: 4.}))
205205
Js.log2("expect {x:7, y:7}:", expectSeven)
206206
}
207+
module TaggedUnions = {
208+
/*
209+
type Circle = {
210+
kind: 1; // Number literal
211+
radius: number;
212+
};
213+
214+
type Square = {
215+
kind: "square"; // String literal
216+
sideLength: number;
217+
};
218+
219+
type Rectangle = {
220+
kind: "rectangle"; // String literal
221+
width: number;
222+
height: number;
223+
};
224+
225+
type Shape = Circle | Square | Rectangle;
226+
227+
function area(shape: Shape): number {
228+
switch (shape.kind) {
229+
case 1: // Circle
230+
return Math.PI * shape.radius ** 2;
231+
case "square": // Square
232+
return shape.sideLength ** 2;
233+
case "rectangle": // Rectangle
234+
return shape.width * shape.height;
235+
default:
236+
throw new Error("Invalid shape kind");
237+
}
238+
}
239+
*/
240+
type circle = {
241+
kind: string,
242+
radius: float,
243+
}
244+
245+
type square = {
246+
kind: string,
247+
sideLength: float,
248+
}
249+
250+
type rectangle = {
251+
kind: string,
252+
width: float,
253+
height: float,
254+
}
255+
256+
type shape =
257+
| Circle(circle)
258+
| Square(square)
259+
| Rectangle(rectangle)
260+
261+
let area = (shape: shape): float => {
262+
switch shape {
263+
| Circle({radius}) => Js.Math._PI *. radius ** 2.
264+
| Square({sideLength}) => sideLength ** 2.
265+
| Rectangle({width, height}) => width *. height
266+
}
267+
}
268+
}

0 commit comments

Comments
 (0)