Skip to content

Commit e429217

Browse files
adding GADT documentation and tutorial
1 parent 6ca65ce commit e429217

File tree

2 files changed

+295
-1
lines changed

2 files changed

+295
-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: 290 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,290 @@
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+
10+
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.
11+
12+
For a quick overview of the use cases, reach for GADTs when:
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+
22+
Suppose a simple variant type that represents the current timezone of a date value. This handles both daylight savings and standard time:
23+
24+
```res example
25+
type timezone =
26+
| EST // standard time
27+
| EDT // daylight time
28+
| CST // standard time
29+
| CDT // daylight time
30+
// etc...
31+
```
32+
Using this variant type, we will end up having functions like this:
33+
```res example
34+
let convert_to_daylight = tz => {
35+
switch tz {
36+
| EST => EDT
37+
| CST => CDT
38+
| EDT | CDT /* or, _ */ => failwith("Invalid timezone provided!")
39+
}
40+
}
41+
```
42+
43+
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.
44+
45+
Lets see if we can find a way for the compiler to help us out with normal variants. We could define another variant type to distinguish the two kinds of timezone.
46+
47+
```res example
48+
type daylight_or_standard =
49+
| Daylight(timezone)
50+
| Standard(timezone)
51+
```
52+
53+
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:
54+
```res example
55+
let invalid_tz1 = Daylight(EST)
56+
let invalid_tz2 = Standard(EDT)
57+
```
58+
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 `daylight_or_standard` variant. That could be a passable solution, but that makes a distinction really would like to do is implement some kind of _subtyping_ relationship. We have two _kinds_ of timezone. This is where GADTs are handy:
59+
60+
```res example
61+
type standard
62+
type daylight
63+
64+
type rec timezone<_> =
65+
| EST: timezone<standard>
66+
| EDT: timezone<daylight>
67+
| CST: timezone<standard>
68+
| CDT: timezone<daylight>
69+
```
70+
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`,
71+
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:
72+
73+
```res example
74+
let convert_to_daylight = tz => {
75+
switch tz {
76+
| EST => EDT
77+
| CST => CDT
78+
}
79+
}
80+
```
81+
82+
The compiler can infer correctly that this function should only take `timezone<standard>` and only output
83+
`timezone<daylight>`. We don't need to add any redundant catchall cases and the compiler will even error if
84+
we try to return a standard timezone from this function. Actually, this seems like it could be a problem,
85+
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:
86+
87+
```res example
88+
let convert_to_daylight = tz => {
89+
switch tz {
90+
| EST => EDT
91+
| CST => CDT
92+
| CDT => CDT
93+
| EDT => EDT
94+
}
95+
}
96+
```
97+
98+
This will complain that `daylight` and `standard` are incompatible. To fix this, we need to explicitly annotate to tell the compiler to accept both:
99+
100+
```res example
101+
let convert_to_daylight : type a. timezone<a> => timezone<daylight> = // ...
102+
```
103+
104+
`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 GADTs give us is that the compiler is not able to help us with type inference as much.
105+
106+
Varying return type
107+
----
108+
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 that works on both `int` or `float`:
109+
110+
```res example
111+
type rec number<_> = Int(int): number<int> | Float(float): number<float>
112+
113+
let add:
114+
type a. (number<a>, number<a>) => a =
115+
(a, b) =>
116+
switch (a, b) {
117+
| (Int(a), Int(b)) => a + b
118+
| (Float(a), Float(b)) => a +. b
119+
}
120+
121+
let foo = add(Int(1), Int(2))
122+
123+
let bar = add(Int(1), Float(2.0)) // the compiler will complain here
124+
```
125+
126+
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`.
127+
128+
We can also use this to avoid returning `option` unnecessarily. This example is adapted from Real World Ocaml, chapter 9. We create an array searching function can be configured to either raise an exception, return an `option`, or provide a `default` value depending on the behavior we want.
129+
130+
```res example
131+
module If_not_found = {
132+
type t<_,_>
133+
}module IfNotFound = {
134+
type rec t<_, _> =
135+
| Raise: t<'a, 'a>
136+
| ReturnNone: t<'a, option<'a>>
137+
| DefaultTo('a): t<'a, 'a>
138+
}
139+
140+
let flexible_find:
141+
type a b. (~f: a => bool, array<a>, IfNotFound.t<a, b>) => b =
142+
(~f, arr, ifNotFound) => {
143+
open IfNotFound
144+
switch Array.find(arr, f) {
145+
| None =>
146+
switch ifNotFound {
147+
| Raise => failwith("No matching item found")
148+
| ReturnNone => None
149+
| DefaultTo(x) => x
150+
}
151+
| Some(x) =>
152+
switch ifNotFound {
153+
| ReturnNone => Some(x)
154+
| Raise => x
155+
| DefaultTo(_) => x
156+
}
157+
}
158+
}
159+
160+
```
161+
162+
Hide and recover Type information Dynamically
163+
---
164+
In a very advanced case that combines many of the above techniques, we can use GADTs to selectively hide and recover type information. This helps us create more generic types.
165+
The below example defines a `num` type similar to our above addition example, but this lets us use `int` and `float` arrays
166+
interchangeably, hiding the implementation type rather than exposing it. This is similar to a regular variant. However, it is a tuple including embedding a `num_ty` and another value.
167+
`num_ty` serves as a type-witness, making it
168+
possible to recover type information that was hidden dynamically. Matching on `num_ty` 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:
169+
170+
```res example
171+
type rec num_ty<'a> =
172+
| Int: num_ty<int>
173+
| Float: num_ty<float>
174+
and num = Num(num_ty<'a>, 'a): num
175+
and num_array = Narray(num_ty<'a>, array<'a>): num_array
176+
177+
let add_int = (x, y) => x + y
178+
let add_float = (x, y) => x +. y
179+
180+
let sum = (Narray(witness, array)) => {
181+
switch witness {
182+
| Int => Num(Int, array->Array.reduce(0, add_int))
183+
| Float => Num(Float, array->Array.reduce(0., add_float))
184+
}
185+
}
186+
```
187+
188+
A Practical Example -- writing bindings:
189+
---
190+
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
191+
of Node's `Stream` API.
192+
193+
This API has a method for binding event handlers, `on`. This takes an event and a callback. The callback accepts different parameters
194+
depending in which event we are binding to. A naive implementation might look similar to this, defining a
195+
separate method for each stream event to wrap the unsafe version of on.
196+
197+
```res example
198+
module Stream = {
199+
type t
200+
201+
@new @module("node:http") external make: unit => t = "stream"
202+
203+
@send external on : (stream, string, 'a) => unit
204+
let onEnd = (stream, callback: unit=> unit) => stream->on("end", callback)
205+
let onData = (stream, callback: ('a => 'b)) => stream->on("", callback)
206+
// etc. ...
207+
}
208+
```
209+
210+
Not only is this quite tedious to write, and quite ugly, but we gain very little from it. The function wrappers even add performance overhead, so we are losing on almost all fronts. If we define subtypes of
211+
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.
212+
213+
Instead, we can use the same GADT technique that let us vary return type to vary the input type.
214+
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
215+
the type signature of the callback and pass this instead of a plain string.
216+
217+
Additionally, we use some type parameters to represent the different types of Streams.
218+
219+
This example is complex, but it enforces tons of useful rules. The wrong event can never be used
220+
with the wrong callback, but it also will never be used with the wrong kind of stream. The compiler will will complain for example if we try to use a `Pipe` event with anything other than a `writable` stream.
221+
222+
The real magic happens in the signature of `on`. Read it carefully, and then look at the examples and try to
223+
follow how the type variables are getting filled in, write it out on paper what each type variable is equal
224+
to if you need and it will soon become clear.
225+
226+
```res example
227+
228+
module Stream = {
229+
type t<'a>
230+
231+
type writable
232+
type readable
233+
234+
type buffer = {buffer: ArrayBuffer.t}
235+
236+
@unboxed
237+
type chunk =
238+
| Str(string)
239+
// Node uses actually its own buffer type, but for the tutorial are just using the stdlib's buffer type.
240+
| Buf(buffer)
241+
242+
type rec event<_, _> =
243+
// "as" here is setting the runtime representation of our constructor
244+
| @as("pipe") Pipe: event<writable, t<readable> => unit>
245+
| @as("end") End: event<'inputStream, option<chunk> => unit>
246+
| @as("data") Data: event<readable, chunk => unit>
247+
248+
@new @module("node:http") external make: unit => t<'a> = "Stream"
249+
250+
@send
251+
external on: (t<'inputStream>, event<'inputStream, 'callback>, 'callback) => unit = "on"
252+
253+
}
254+
255+
let writer = Stream.Writable.make()
256+
let reader = Stream.Readable.make()
257+
// Types will be correctly inferred for each callback, based on the event parameter provided
258+
writer->Stream.on(Pipe, r => {
259+
Js.log("Piping has started")
260+
261+
r->Stream.on(Data, chunk =>
262+
switch chunk {
263+
| Stream.Str(s) => Js.log(s)
264+
| Stream.Buf(buffer) => Js.log(buffer)
265+
}
266+
)
267+
})
268+
269+
writer->Stream.on(End, _ => Js.log("End reached"))
270+
271+
```
272+
273+
This example is only over a tiny, imaginary subset of node's Stream API, but it shows a real-life example
274+
where GADTs are all but indispensable.
275+
276+
Conclusion
277+
-----
278+
While GADTs can make your types extra-expressive and get more safety, with great power comes great
279+
responsibility. Code that uses GADTs can sometimes be too clever for its own good. The type errors you
280+
encounter will be more difficult to understand, and the compiler sometimes requires extra help to properly
281+
type your code.
282+
283+
However, There are definite situations where GADTs are the _right_ decision
284+
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.
285+
would lead to a much more complex and error prone interface.
286+
287+
Ordinary variants are not necessarily _simple_ therefore, and neither are GADTs necessarily _complex_.
288+
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.
289+
When your logic is simple, it's best to reach for a simpler tool and avoid the cognitive overhead.
290+
The only way to get good at identifying which the situation calls for is to try out

0 commit comments

Comments
 (0)