Skip to content

Commit 7ced1f0

Browse files
Add GADT documentation to the manual (#1096)
* adding GADT documentation and tutorial * code formatting fixed in GADT man page * Making changes according to feedback * Formatting fix * Fixing remaining feedback
1 parent d59ecc9 commit 7ced1f0

File tree

2 files changed

+305
-1
lines changed

2 files changed

+305
-1
lines changed

data/sidebar_manual_v1200.json

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,5 +58,9 @@
5858
"build-performance",
5959
"warning-numbers"
6060
],
61-
"Advanced Features": ["extensible-variant", "scoped-polymorphic-types"]
61+
"Advanced Features": [
62+
"extensible-variant",
63+
"scoped-polymorphic-types",
64+
"generalized-algebraic-data-types"
65+
]
6266
}
Lines changed: 300 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,300 @@
1+
---
2+
title: "Generalized Algebraic Data Types"
3+
description: "Generalized Algebraic Data Types in ReScript"
4+
canonical: "/docs/manual/v12.0.0/generalized-algebraic-data-types"
5+
---
6+
7+
# Generalized Algebraic Data Types
8+
9+
Generalized Algebraic Data Types (GADTs) are an advanced feature of ReScript's type system. "Generalized" can be somewhat of a misnomer -- what they actually allow you to do is add some extra type-specificity to your variants. Using a GADT, you can give the individual cases of a variant _different_ types.
10+
11+
For a quick overview of the use cases, reach for GADTs when:
12+
13+
1. You need to distinguish between different members of a variant at the type level.
14+
2. You want to "hide" type information in a type-safe way, without resorting to casts.
15+
3. You need a function to return a different type depending on its input.
16+
17+
GADTs usually are overkill, but when you need them, you need them! Understanding them from first principles is difficult, so it is best to explain through some motivating examples.
18+
19+
## Distinguishing Constructors (Subtyping)
20+
21+
Suppose a simple variant type that represents the current timezone of a date value. This handles both daylight savings and standard time:
22+
23+
```res example
24+
type timezone =
25+
| EST // standard time
26+
| EDT // daylight time
27+
| CST // standard time
28+
| CDT // daylight time
29+
// etc...
30+
```
31+
32+
Using this variant type, we will end up having functions like this:
33+
34+
```res example
35+
let convertToDaylight = tz => {
36+
switch tz {
37+
| EST => EDT
38+
| CST => CDT
39+
| EDT | CDT /* or, _ */ => failwith("Invalid timezone provided!")
40+
}
41+
}
42+
```
43+
44+
This function is only valid for a subset of our variant type's constructors but we can't handle this in a type-safe way using regular variants. We have to enforce that at runtime -- and moreover the compiler can't help us ensure we are failing only in the invalid cases. We are back to dynamically checking validity like we would in a language without static typing. If you work with a large variant type long enough, you will frequently find yourself writing repetitive catchall `switch` statements like the above, and for little actual benefit. The compiler should be able to help us here.
45+
46+
Let's see if we can find a way for the compiler to help us with normal variants. We could define another variant type to distinguish the two kinds of timezone.
47+
48+
```res example
49+
type daylightOrStandard =
50+
| Daylight(timezone)
51+
| Standard(timezone)
52+
```
53+
54+
This has a lot of problems. For one, it's cumbersome and redundant. We would now have to pattern-match twice whenever we deal with a timezone that's wrapped up here. The compiler will force us to check whether we are dealing with daylight or standard time, but notice that there's nothing stopping us from providing invalid timezones to these constructors:
55+
56+
```res example
57+
let invalidTz1 = Daylight(EST)
58+
let invalidTz2 = Standard(EDT)
59+
```
60+
61+
Consequently, we still have to write our redundant catchall cases. We could define daylight savings time and standard time as two _separate_ types, and unify those in our `daylightOrStandard` variant.
62+
That could be a passable solution, but what we would really like to do is implement some kind of subtyping relationship.
63+
We have two _kinds_ of timezone. This is where GADTs are handy:
64+
65+
```res example
66+
type standard
67+
type daylight
68+
69+
type rec timezone<_> =
70+
| EST: timezone<standard>
71+
| EDT: timezone<daylight>
72+
| CST: timezone<standard>
73+
| CDT: timezone<daylight>
74+
```
75+
76+
We define our type with a type parameter. We manually annotate each constructor, providing it with the correct type parameter indicating whether it is standard or daylight. Each constructor is a `timezone`,
77+
but we've added another level of specificity using a type parameter. Constructors are now understood to be `standard` or `daylight` at the _type_ level. Now we can fix our function like this:
78+
79+
```res example
80+
let convertToDaylight = tz => {
81+
switch tz {
82+
| EST => EDT
83+
| CST => CDT
84+
}
85+
}
86+
```
87+
88+
The compiler can infer correctly that this function should only take `timezone<standard>` and only output
89+
`timezone<daylight>`. We don't need to add any redundant catchall cases and the compiler will even error if
90+
we try to return a standard timezone from this function. Actually, this seems like it could be a problem,
91+
we still want to be able to match on all cases of the variant sometimes, and a naive attempt at this will not pass the type checker. A naive example will fail:
92+
93+
```res example
94+
let convertToDaylight = tz =>
95+
switch tz {
96+
| EST => EDT
97+
| CST => CDT
98+
| CDT => CDT
99+
| EDT => EDT
100+
}
101+
```
102+
103+
This will complain that `daylight` and `standard` are incompatible. To fix this, we need to explicitly annotate to tell the compiler to accept both:
104+
105+
```res example
106+
let convertToDaylight : type a. timezone<a> => timezone<daylight> = // ...
107+
```
108+
109+
The syntax `type a.` here defines a _locally abstract type_ which basically tells the compiler that the type parameter a is some specific type, but we don't care what it is. The cost of the extra specificity and safety that
110+
GADTs give us is that the compiler less able to help us with type inference.
111+
112+
## Varying return type
113+
114+
Sometimes, a function should have a different return type based on what you give it, and GADTs are how we can do this in a type-safe way. We can implement a generic `add` function[^1] that works on both `int` or `float`:
115+
116+
[^1]: In ReScript v12, the built-in operators are already generic, but we use them in this example for simplicity.
117+
118+
```res example
119+
type rec number<_> = Int(int): number<int> | Float(float): number<float>
120+
121+
let add:
122+
type a. (number<a>, number<a>) => a =
123+
(a, b) =>
124+
switch (a, b) {
125+
| (Int(a), Int(b)) => a + b
126+
| (Float(a), Float(b)) => a +. b
127+
}
128+
129+
let foo = add(Int(1), Int(2))
130+
131+
let bar = add(Int(1), Float(2.0)) // the compiler will complain here
132+
```
133+
134+
How does this work? The key thing is the function signature for add. The `number` GADT is acting as a _type witness_. We have told the compiler that the type parameter for `number` will be the same as the type we return -- both are set to `a`. So if we provide a `number<int>`, `a` equals `int`, and the function will therefore return an `int`.
135+
136+
We can also use this to avoid returning `option` unnecessarily. We create an array searching function which either raises an exception, returns an `option`, or provides a `default` value depending on the behavior we ask for.[^2]
137+
138+
[^2]: This example is adapted from [here](https://dev.realworldocaml.org/gadts.html).
139+
140+
```res example
141+
module If_not_found = {
142+
type t<_,_>
143+
}module IfNotFound = {
144+
type rec t<_, _> =
145+
| Raise: t<'a, 'a>
146+
| ReturnNone: t<'a, option<'a>>
147+
| DefaultTo('a): t<'a, 'a>
148+
}
149+
150+
let flexible_find:
151+
type a b. (~f: a => bool, array<a>, IfNotFound.t<a, b>) => b =
152+
(~f, arr, ifNotFound) => {
153+
open IfNotFound
154+
switch Array.find(arr, f) {
155+
| None =>
156+
switch ifNotFound {
157+
| Raise => failwith("No matching item found")
158+
| ReturnNone => None
159+
| DefaultTo(x) => x
160+
}
161+
| Some(x) =>
162+
switch ifNotFound {
163+
| ReturnNone => Some(x)
164+
| Raise => x
165+
| DefaultTo(_) => x
166+
}
167+
}
168+
}
169+
170+
```
171+
172+
## Hide and recover Type information Dynamically
173+
174+
In an advanced case that combines the above techniques, we can use GADTs to selectively hide and recover type information. This helps us create more generic types.
175+
The below example defines a `num` type similar to our above addition example, but this lets us use `int` and `float` arrays
176+
interchangeably, hiding the implementation type rather than exposing it. This is similar to a regular variant. However, it is a tuple including embedding a `numTy` and another value.
177+
`numTy` serves as a type-witness, making it
178+
possible to recover type information that was hidden dynamically. Matching on `numTy` will "reveal" the type of the other value in the pair. We can use this to write a generic sum function over arrays of numbers:
179+
180+
```res example
181+
type rec numTy<'a> =
182+
| Int: numTy<int>
183+
| Float: numTy<float>
184+
and num = Num(numTy<'a>, 'a): num
185+
and num_array = Narray(numTy<'a>, array<'a>): num_array
186+
187+
let addInt = (x, y) => x + y
188+
let addFloat = (x, y) => x +. y
189+
190+
let sum = (Narray(witness, array)) => {
191+
switch witness {
192+
| Int => Num(Int, array->Array.reduce(0, addInt))
193+
| Float => Num(Float, array->Array.reduce(0., addFloat))
194+
}
195+
}
196+
```
197+
198+
## A Practical Example -- writing bindings:
199+
200+
Javascript libraries that are highly polymorphic or use inheritance can benefit hugely from GADTs, but they can be useful for bindings even in other cases. The following examples are writing bindings to a simplified
201+
of Node's `Stream` API.
202+
203+
This API has a method for binding event handlers, `on`. This takes an event and a callback. The callback accepts different parameters
204+
depending on which event we are binding to. A naive implementation might look similar to this, defining a
205+
separate method for each stream event to wrap the unsafe version of `on`.
206+
207+
```res example
208+
module Stream = {
209+
type t
210+
211+
@new @module("node:http") external make: unit => t = "stream"
212+
213+
@send external on : (stream, string, 'a) => unit
214+
let onEnd = (stream, callback: unit=> unit) => stream->on("end", callback)
215+
let onData = (stream, callback: ('a => 'b)) => stream->on("", callback)
216+
// etc. ...
217+
}
218+
```
219+
220+
Not only is this quite tedious to write and quite ugly, but we gain very little in return. The function wrappers even add performance overhead, so we are losing on all fronts. If we define subtypes of
221+
Stream like `Readable` or `Writable`, which have all sorts of special interactions with the callback that jeopardize our type-safety, we are going to be in even deeper trouble.
222+
223+
Instead, we can use the same GADT technique that let us vary return type to vary the input type.
224+
Not only are we able to now just use a single method, but the compiler will guarantee we are always using the correct callback type for the given event. We simply define an event GADT which specifies
225+
the type signature of the callback and pass this instead of a plain string.
226+
227+
Additionally, we use some type parameters to represent the different types of Streams.
228+
229+
This example is complex, but it enforces tons of useful rules. The wrong event can never be used
230+
with the wrong callback, but it also will never be used with the wrong kind of stream. The compiler will for example complain if we try to use a `Pipe` event with anything other than a `writable` stream.
231+
232+
The real magic happens in the signature of `on`. Read it carefully, and then look at the examples and try to
233+
follow how the type variables are getting filled in, write it out on paper what each type variable is equal
234+
to if you need and it will soon become clear.
235+
236+
```res example
237+
238+
module Stream = {
239+
type t<'a>
240+
241+
type writable
242+
type readable
243+
244+
type buffer = {buffer: ArrayBuffer.t}
245+
246+
@unboxed
247+
type chunk =
248+
| Str(string)
249+
// Node uses actually its own buffer type, but for the tutorial we are using the stdlib's buffer type.
250+
| Buf(buffer)
251+
252+
type rec event<_, _> =
253+
// "as" here is setting the runtime representation of our constructor
254+
| @as("pipe") Pipe: event<writable, t<readable> => unit>
255+
| @as("end") End: event<'inputStream, option<chunk> => unit>
256+
| @as("data") Data: event<readable, chunk => unit>
257+
258+
@new @module("node:http") external make: unit => t<'a> = "Stream"
259+
260+
@send
261+
external on: (t<'inputStream>, event<'inputStream, 'callback>, 'callback) => unit = "on"
262+
263+
}
264+
265+
let writer = Stream.Writable.make()
266+
let reader = Stream.Readable.make()
267+
// Types will be correctly inferred for each callback, based on the event parameter provided
268+
writer->Stream.on(Pipe, r => {
269+
Console.log("Piping has started")
270+
271+
r->Stream.on(Data, chunk =>
272+
switch chunk {
273+
| Stream.Str(s) => Console.log(s)
274+
| Stream.Buf(buffer) => Console.log(buffer)
275+
}
276+
)
277+
})
278+
279+
writer->Stream.on(End, _ => Console.log("End reached"))
280+
281+
```
282+
283+
This example is only over a tiny, imaginary subset of Node's Stream API, but it shows a real-life example
284+
where GADTs are all but indispensable.
285+
286+
## Conclusion
287+
288+
While GADTs can make your types extra-expressive and provide more safety, with great power comes great
289+
responsibility. Code that uses GADTs can sometimes be too clever for its own good. The type errors you
290+
encounter will be more difficult to understand, and the compiler sometimes requires extra help to properly
291+
type your code.
292+
293+
However, there are definite situations where GADTs are the _right_ decision
294+
and will _simplify_ your code and help you avoid bugs, even rendering some bugs impossible. The `Stream` example above is a good example where the "simpler" alternative of using regular variants or even strings
295+
would lead to a much more complex and error prone interface.
296+
297+
Ordinary variants are not necessarily _simple_ therefore, and neither are GADTs necessarily _complex_.
298+
The choice is rather which tool is the right one for the job. When your logic is complex, the highly expressive nature of GADTs can make it simpler to capture that logic.
299+
When your logic is simple, it's best to reach for a simpler tool and avoid the cognitive overhead.
300+
The only way to get good at identifying which tool to use in a given situation is to practice and experiment with both.

0 commit comments

Comments
 (0)