Skip to content

Commit 71c9f55

Browse files
fhammerschmidtYawarRaza7349
authored andcommitted
Copy advanced guides (#1102)
* Copy module function guide to v12 docs * Copy gadt guide to v11 docs * Small fix
1 parent 99813c8 commit 71c9f55

File tree

5 files changed

+638
-4
lines changed

5 files changed

+638
-4
lines changed

data/sidebar_manual_v1100.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,8 @@
3838
"Advanced Features": [
3939
"extensible-variant",
4040
"scoped-polymorphic-types",
41-
"module-functions"
41+
"module-functions",
42+
"generalized-algebraic-data-types"
4243
],
4344
"JavaScript Interop": [
4445
"interop-cheatsheet",

data/sidebar_manual_v1200.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
"Advanced Features": [
6262
"extensible-variant",
6363
"scoped-polymorphic-types",
64+
"module-functions",
6465
"generalized-algebraic-data-types"
6566
]
6667
}
Lines changed: 298 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,298 @@
1+
---
2+
title: "Generalized Algebraic Data Types"
3+
description: "Generalized Algebraic Data Types in ReScript"
4+
canonical: "/docs/manual/v11.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 IfNotFound = {
142+
type rec t<_, _> =
143+
| Raise: t<'a, 'a>
144+
| ReturnNone: t<'a, option<'a>>
145+
| DefaultTo('a): t<'a, 'a>
146+
}
147+
148+
let flexible_find:
149+
type a b. (~f: a => bool, array<a>, IfNotFound.t<a, b>) => b =
150+
(~f, arr, ifNotFound) => {
151+
open IfNotFound
152+
switch Array.find(arr, f) {
153+
| None =>
154+
switch ifNotFound {
155+
| Raise => failwith("No matching item found")
156+
| ReturnNone => None
157+
| DefaultTo(x) => x
158+
}
159+
| Some(x) =>
160+
switch ifNotFound {
161+
| ReturnNone => Some(x)
162+
| Raise => x
163+
| DefaultTo(_) => x
164+
}
165+
}
166+
}
167+
168+
```
169+
170+
## Hide and recover Type information Dynamically
171+
172+
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.
173+
The below example defines a `num` type similar to our above addition example, but this lets us use `int` and `float` arrays
174+
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.
175+
`numTy` serves as a type-witness, making it
176+
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:
177+
178+
```res example
179+
type rec numTy<'a> =
180+
| Int: numTy<int>
181+
| Float: numTy<float>
182+
and num = Num(numTy<'a>, 'a): num
183+
and num_array = Narray(numTy<'a>, array<'a>): num_array
184+
185+
let addInt = (x, y) => x + y
186+
let addFloat = (x, y) => x +. y
187+
188+
let sum = (Narray(witness, array)) => {
189+
switch witness {
190+
| Int => Num(Int, array->Array.reduce(0, addInt))
191+
| Float => Num(Float, array->Array.reduce(0., addFloat))
192+
}
193+
}
194+
```
195+
196+
## A Practical Example -- writing bindings:
197+
198+
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
199+
of Node's `Stream` API.
200+
201+
This API has a method for binding event handlers, `on`. This takes an event and a callback. The callback accepts different parameters
202+
depending on which event we are binding to. A naive implementation might look similar to this, defining a
203+
separate method for each stream event to wrap the unsafe version of `on`.
204+
205+
```res example
206+
module Stream = {
207+
type t
208+
209+
@new @module("node:http") external make: unit => t = "stream"
210+
211+
@send external on : (stream, string, 'a) => unit
212+
let onEnd = (stream, callback: unit=> unit) => stream->on("end", callback)
213+
let onData = (stream, callback: ('a => 'b)) => stream->on("", callback)
214+
// etc. ...
215+
}
216+
```
217+
218+
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
219+
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.
220+
221+
Instead, we can use the same GADT technique that let us vary return type to vary the input type.
222+
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
223+
the type signature of the callback and pass this instead of a plain string.
224+
225+
Additionally, we use some type parameters to represent the different types of Streams.
226+
227+
This example is complex, but it enforces tons of useful rules. The wrong event can never be used
228+
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.
229+
230+
The real magic happens in the signature of `on`. Read it carefully, and then look at the examples and try to
231+
follow how the type variables are getting filled in, write it out on paper what each type variable is equal
232+
to if you need and it will soon become clear.
233+
234+
```res example
235+
236+
module Stream = {
237+
type t<'a>
238+
239+
type writable
240+
type readable
241+
242+
type buffer = {buffer: ArrayBuffer.t}
243+
244+
@unboxed
245+
type chunk =
246+
| Str(string)
247+
// Node uses actually its own buffer type, but for the tutorial we are using the stdlib's buffer type.
248+
| Buf(buffer)
249+
250+
type rec event<_, _> =
251+
// "as" here is setting the runtime representation of our constructor
252+
| @as("pipe") Pipe: event<writable, t<readable> => unit>
253+
| @as("end") End: event<'inputStream, option<chunk> => unit>
254+
| @as("data") Data: event<readable, chunk => unit>
255+
256+
@new @module("node:http") external make: unit => t<'a> = "Stream"
257+
258+
@send
259+
external on: (t<'inputStream>, event<'inputStream, 'callback>, 'callback) => unit = "on"
260+
261+
}
262+
263+
let writer = Stream.Writable.make()
264+
let reader = Stream.Readable.make()
265+
// Types will be correctly inferred for each callback, based on the event parameter provided
266+
writer->Stream.on(Pipe, r => {
267+
Console.log("Piping has started")
268+
269+
r->Stream.on(Data, chunk =>
270+
switch chunk {
271+
| Stream.Str(s) => Console.log(s)
272+
| Stream.Buf(buffer) => Console.log(buffer)
273+
}
274+
)
275+
})
276+
277+
writer->Stream.on(End, _ => Console.log("End reached"))
278+
279+
```
280+
281+
This example is only over a tiny, imaginary subset of Node's Stream API, but it shows a real-life example
282+
where GADTs are all but indispensable.
283+
284+
## Conclusion
285+
286+
While GADTs can make your types extra-expressive and provide more safety, with great power comes great
287+
responsibility. Code that uses GADTs can sometimes be too clever for its own good. The type errors you
288+
encounter will be more difficult to understand, and the compiler sometimes requires extra help to properly
289+
type your code.
290+
291+
However, there are definite situations where GADTs are the _right_ decision
292+
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
293+
would lead to a much more complex and error prone interface.
294+
295+
Ordinary variants are not necessarily _simple_ therefore, and neither are GADTs necessarily _complex_.
296+
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.
297+
When your logic is simple, it's best to reach for a simpler tool and avoid the cognitive overhead.
298+
The only way to get good at identifying which tool to use in a given situation is to practice and experiment with both.

pages/docs/manual/v12.0.0/generalized-algebraic-data-types.mdx

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -138,9 +138,7 @@ We can also use this to avoid returning `option` unnecessarily. We create an arr
138138
[^2]: This example is adapted from [here](https://dev.realworldocaml.org/gadts.html).
139139

140140
```res example
141-
module If_not_found = {
142-
type t<_,_>
143-
}module IfNotFound = {
141+
module IfNotFound = {
144142
type rec t<_, _> =
145143
| Raise: t<'a, 'a>
146144
| ReturnNone: t<'a, option<'a>>

0 commit comments

Comments
 (0)