Lesson 15 of 15
Discriminated Unions
Discriminated Unions
Discriminated Unions (DUs) let you define types with named cases, each possibly carrying data:
type Shape =
| Circle of float
| Rectangle of float * float
let area shape = match shape with
| Circle r -> 3.14159 * r * r
| Rectangle (w, h) -> w * h
DUs are ideal for modeling alternatives — each case is a distinct constructor.
Use match to pattern-match on the case and extract the data.
Your Task
Define a DU Expr with three cases:
Num of int— a literal numberAdd of int * int— addition of two numbersMul of int * int— multiplication of two numbers
Write a function eval that pattern-matches on an Expr and returns an int.
JS Transpiler loading...
Loading...
Click "Run" to execute your code.