Skip to content

Commit a84d5e5

Browse files
authored
docs: replace usage of functor with module functions (#858)
* docs: replace usage of functor with module functions * create module-functions page * add example for module functions * docs - add js output to module function example * add another example * more module function examples * one less react example * editing pass
1 parent 56b2426 commit a84d5e5

File tree

3 files changed

+327
-15
lines changed

3 files changed

+327
-15
lines changed

data/sidebar_manual_latest.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,8 @@
3737
],
3838
"Advanced Features": [
3939
"extensible-variant",
40-
"scoped-polymorphic-types"
40+
"scoped-polymorphic-types",
41+
"module-functions"
4142
],
4243
"JavaScript Interop": [
4344
"interop-cheatsheet",
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,311 @@
1+
---
2+
title: "Module Functions"
3+
description: "Module Functions in ReScript"
4+
canonical: "/docs/manual/latest/module-functions"
5+
---
6+
7+
# Module Functions
8+
9+
Module functions can be used to create modules based on types, values, or functions from other modules.
10+
This is a powerful tool that can be used to create abstractions and reusable code that might not be possible with functions, or might have a runtime cost if done with functions.
11+
12+
This is an advanced part of ReScript and you can generally get by with normal values and functions.
13+
14+
## Quick example
15+
Next.js has a `useParams` hook that returns an unknown type,
16+
and it's up to the developer in TypeScript to add a type annotation for the parameters returned by the hook.
17+
```TS
18+
const params = useParams<{ tag: string; item: string }>()
19+
```
20+
21+
In ReScript we can create a module function that will return a typed response for the `useParams` hook.
22+
<CodeTab labels={["ReScript", "JS Output"]}>
23+
```res example
24+
module Next = {
25+
// define our module function
26+
module MakeParams = (Params: { type t }) => {
27+
@module("next/navigation")
28+
external useParams: unit => Params.t = "useParams"
29+
/* You can use values from the function parameter, such as Params.t */
30+
}
31+
}
32+
33+
module Component: {
34+
@react.component
35+
let make: unit => Jsx.element
36+
} = {
37+
// Create a module that matches the module type expected by Next.MakeParams
38+
module P = {
39+
type t = {
40+
tag: string,
41+
item: string,
42+
}
43+
}
44+
45+
// Create a new module using the Params module we created and the Next.MakeParams module function
46+
module Params = Next.MakeParams(P)
47+
48+
@react.component
49+
let make = () => {
50+
// Use the functions, values, or types created by the module function
51+
let params = Params.useParams()
52+
<div>
53+
<p>
54+
{React.string("Tag: " ++ params.tag /* params is fully typed! */)}
55+
</p>
56+
<p> {React.string("Item: " ++ params.item)} </p>
57+
</div>
58+
}
59+
}
60+
```
61+
```js
62+
// Generated by ReScript, PLEASE EDIT WITH CARE
63+
64+
import * as $$Navigation from "next/navigation";
65+
import * as JsxRuntime from "react/jsx-runtime";
66+
67+
function MakeParams(Params) {
68+
return {};
69+
}
70+
71+
var Next = {
72+
MakeParams: MakeParams
73+
};
74+
75+
function Playground$Component(props) {
76+
var params = $$Navigation.useParams();
77+
return JsxRuntime.jsxs("div", {
78+
children: [
79+
JsxRuntime.jsx("p", {
80+
children: "Tag: " + params.tag
81+
}),
82+
JsxRuntime.jsx("p", {
83+
children: "Item: " + params.item
84+
})
85+
]
86+
});
87+
}
88+
89+
var Component = {
90+
make: Playground$Component
91+
};
92+
93+
export {
94+
Next ,
95+
Component ,
96+
}
97+
/* next/navigation Not a pure module */
98+
99+
```
100+
</ CodeTab>
101+
102+
## Sharing a type with an external binding
103+
This becomes incredibly useful when you need to have types that are unique to a project but shared across multiple components.
104+
Let's say you want to create a library with a `getEnv` function to load in environment variables found in `import.meta.env`.
105+
```res
106+
@val external env: 'a = "import.meta.env"
107+
108+
let getEnv = () => {
109+
env
110+
}
111+
```
112+
It's not possible to define types for this that will work for every project, so we just set it as 'a and the consumer of our library can define the return type.
113+
```res
114+
type t = {"LOG_LEVEL": string}
115+
116+
let values: t = getEnv()
117+
```
118+
This isn't great and it doesn't take advantage of ReScript's type system and ability to use types without type definitions, and it can't be easily shared across our application.
119+
120+
We can instead create a module function that can return a module that has contains a `getEnv` function that has a typed response.
121+
```res
122+
module MakeEnv = (
123+
E: {
124+
type t
125+
},
126+
) => {
127+
@val external env: E.t = "import.meta.env"
128+
129+
let getEnv = () => {
130+
env
131+
}
132+
}
133+
```
134+
And now consumers of our library can define the types and create a custom version of the hook for their application.
135+
Notice that in the JavaScript output that the `import.meta.env` is used directly and doesn't require any function calls or runtime overhead.
136+
137+
<CodeTab labels={["ReScript", "JS Output"]}>
138+
```res
139+
module Env = MakeEnv({
140+
type t = {"LOG_LEVEL": string}
141+
})
142+
143+
let values = Env.getEnv()
144+
```
145+
```js
146+
var Env = {
147+
getEnv: getEnv
148+
};
149+
150+
var values = import.meta.env;
151+
```
152+
</ CodeTab>
153+
154+
## Shared functions
155+
You might want to share functions across modules, like a way to log a value or render it in React.
156+
Here's an example of module function that takes in a type and a transform to string function.
157+
158+
```res
159+
module MakeDataModule = (
160+
T: {
161+
type t
162+
let toString: t => string
163+
},
164+
) => {
165+
type t = T.t
166+
let log = a => Console.log("The value is " ++ T.toString(a))
167+
168+
module Render = {
169+
@react.component
170+
let make = (~value) => value->T.toString->React.string
171+
}
172+
}
173+
```
174+
You can now take a module with a type of `t` and a `toString` function and create a new module that has the `log` function and the `Render` component.
175+
<CodeTab labels={["ReScript", "JS Output"]}>
176+
```res
177+
module Person = {
178+
type t = { firstName: string, lastName: string }
179+
let toString = person => person.firstName ++ person.lastName
180+
}
181+
182+
module PersonData = MakeDataModule(Person)
183+
```
184+
185+
```js
186+
// Notice that none of the JS output references the MakeDataModule function
187+
188+
function toString(person) {
189+
return person.firstName + person.lastName;
190+
}
191+
192+
var Person = {
193+
toString: toString
194+
};
195+
196+
function log(a) {
197+
console.log("The value is " + toString(a));
198+
}
199+
200+
function Person$MakeDataModule$Render(props) {
201+
return toString(props.value);
202+
}
203+
204+
var Render = {
205+
make: Person$MakeDataModule$Render
206+
};
207+
208+
var PersonData = {
209+
log: log,
210+
Render: Render
211+
};
212+
```
213+
</CodeTab>
214+
215+
Now the `PersonData` module has the functions from the `MakeDataModule`.
216+
<CodeTab labels={["ReScript", "JS Output"]}>
217+
```res
218+
@react.component
219+
let make = (~person) => {
220+
let handleClick = _ => PersonData.log(person)
221+
<div>
222+
{React.string("Hello ")}
223+
<PersonData.Render value=person />
224+
<button onClick=handleClick>
225+
{React.string("Log value to console")}
226+
</button>
227+
</div>
228+
}
229+
```
230+
```js
231+
function Person$1(props) {
232+
var person = props.person;
233+
var handleClick = function (param) {
234+
log(person);
235+
};
236+
return JsxRuntime.jsxs("div", {
237+
children: [
238+
"Hello ",
239+
JsxRuntime.jsx(Person$MakeDataModule$Render, {
240+
value: person
241+
}),
242+
JsxRuntime.jsx("button", {
243+
children: "Log value to console",
244+
onClick: handleClick
245+
})
246+
]
247+
});
248+
}
249+
```
250+
</CodeTab>
251+
252+
## Dependency injection
253+
Module functions can be used for dependency injection.
254+
Here's an example of injecting in some config values into a set of functions to access a database.
255+
<CodeTab labels={["ReScript", "JS Output"]}>
256+
```res
257+
module type DbConfig = {
258+
let host: string
259+
let database: string
260+
let username: string
261+
let password: string
262+
}
263+
264+
module MakeDbConnection = (Config: DbConfig) => {
265+
type client = {
266+
write: string => unit,
267+
read: string => string,
268+
}
269+
@module("database.js")
270+
external makeClient: (string, string, string, string) => client = "makeClient"
271+
272+
let client = makeClient(Config.host, Config.database, Config.username, Config.password)
273+
}
274+
275+
module Db = MakeDbConnection({
276+
let host = "localhost"
277+
let database = "mydb"
278+
let username = "root"
279+
let password = "password"
280+
})
281+
282+
let updateDb = Db.client.write("new value")
283+
```
284+
```js
285+
// Generated by ReScript, PLEASE EDIT WITH CARE
286+
287+
import * as DatabaseJs from "database.js";
288+
289+
function MakeDbConnection(Config) {
290+
var client = DatabaseJs.makeClient(Config.host, Config.database, Config.username, Config.password);
291+
return {
292+
client: client
293+
};
294+
}
295+
296+
var client = DatabaseJs.makeClient("localhost", "mydb", "root", "password");
297+
298+
var Db = {
299+
client: client
300+
};
301+
302+
var updateDb = client.write("new value");
303+
304+
export {
305+
MakeDbConnection ,
306+
Db ,
307+
updateDb ,
308+
}
309+
/* client Not a pure module */
310+
```
311+
</CodeTab>

pages/docs/manual/latest/module.mdx

+14-14
Original file line numberDiff line numberDiff line change
@@ -413,22 +413,22 @@ type state = int
413413
let render: string => string
414414
```
415415

416-
## Module Functions (functors)
416+
## Module Functions
417417

418418
Modules can be passed to functions! It would be the equivalent of passing a file
419419
as a first-class item. However, modules are at a different "layer" of the
420420
language than other common concepts, so we can't pass them to *regular*
421-
functions. Instead, we pass them to special functions called "functors".
421+
functions. Instead, we pass them to special functions called module functions.
422422

423-
The syntax for defining and using functors is very much like the syntax
423+
The syntax for defining and using module functions is very much like the syntax
424424
for defining and using regular functions. The primary differences are:
425425

426-
- Functors use the `module` keyword instead of `let`.
427-
- Functors take modules as arguments and return a module.
428-
- Functors *require* annotating arguments.
429-
- Functors must start with a capital letter (just like modules/signatures).
426+
- Module functions use the `module` keyword instead of `let`.
427+
- Module functions take modules as arguments and return a module.
428+
- Module functions *require* annotating arguments.
429+
- Module functions must start with a capital letter (just like modules/signatures).
430430

431-
Here's an example `MakeSet` functor, that takes in a module of the type
431+
Here's an example `MakeSet` module function, that takes in a module of the type
432432
`Comparable` and returns a new set that can contain such comparable items.
433433

434434
<CodeTab labels={["ReScript", "JS Output"]}>
@@ -482,7 +482,7 @@ function MakeSet(Item) {
482482

483483
</CodeTab>
484484

485-
Functors can be applied using function application syntax. In this case, we're
485+
Module functions can be applied using function application syntax. In this case, we're
486486
creating a set, whose items are pairs of integers.
487487

488488
<CodeTab labels={["ReScript", "JS Output"]}>
@@ -525,12 +525,12 @@ var SetOfIntPairs = {
525525

526526
### Module functions types
527527

528-
Like with module types, functor types also act to constrain and hide what we may
529-
assume about functors. The syntax for functor types are consistent with those
528+
Like with module types, module function types also act to constrain and hide what we may
529+
assume about module functions. The syntax for module function types are consistent with those
530530
for function types, but with types capitalized to represent the signatures of
531-
modules the functor accepts as arguments and return values. In the
531+
modules the module functions accepts as arguments and return values. In the
532532
previous example, we're exposing the backing type of a set; by giving `MakeSet`
533-
a functor signature, we can hide the underlying data structure!
533+
a module function signature, we can hide the underlying data structure!
534534

535535
<CodeTab labels={["ReScript", "JS Output"]}>
536536

@@ -566,4 +566,4 @@ Please note that modules with an exotic filename will not be accessible from oth
566566

567567
## Tips & Tricks
568568

569-
Modules and functors are at a different "layer" of language than the rest (functions, let bindings, data structures, etc.). For example, you can't easily pass them into a tuple or record. Use them judiciously, if ever! Lots of times, just a record or a function is enough.
569+
Modules and module functions are at a different "layer" of language than the rest (functions, let bindings, data structures, etc.). For example, you can't easily pass them into a tuple or record. Use them judiciously, if ever! Lots of times, just a record or a function is enough.

0 commit comments

Comments
 (0)