Skip to content

docs: replace usage of functor with module functions #858

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Nov 26, 2024
3 changes: 2 additions & 1 deletion data/sidebar_manual_latest.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
],
"Advanced Features": [
"extensible-variant",
"scoped-polymorphic-types"
"scoped-polymorphic-types",
"module-functions"
],
"JavaScript Interop": [
"interop-cheatsheet",
Expand Down
311 changes: 311 additions & 0 deletions pages/docs/manual/latest/module-functions.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,311 @@
---
title: "Module Functions"
description: "Module Functions in ReScript"
canonical: "/docs/manual/latest/module-functions"
---

# Module Functions

Module functions can be used to create modules based on types, values, or functions from other modules.
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.

This is an advanced part of ReScript and you can generally get by with normal values and functions.

## Quick example
Next.js has a `useParams` hook that returns an unknown type,
and it's up to the developer in TypeScript to add a type annotation for the parameters returned by the hook.
```TS
const params = useParams<{ tag: string; item: string }>()
```

In ReScript we can create a module function that will return a typed response for the `useParams` hook.
<CodeTab labels={["ReScript", "JS Output"]}>
```res example
module Next = {
// define our module function
module MakeParams = (Params: { type t }) => {
@module("next/navigation")
external useParams: unit => Params.t = "useParams"
/* You can use values from the function parameter, such as Params.t */
}
}

module Component: {
@react.component
let make: unit => Jsx.element
} = {
// Create a module that matches the module type expected by Next.MakeParams
module P = {
type t = {
tag: string,
item: string,
}
}

// Create a new module using the Params module we created and the Next.MakeParams module function
module Params = Next.MakeParams(P)

@react.component
let make = () => {
// Use the functions, values, or types created by the module function
let params = Params.useParams()
<div>
<p>
{React.string("Tag: " ++ params.tag /* params is fully typed! */)}
</p>
<p> {React.string("Item: " ++ params.item)} </p>
</div>
}
}
```
```js
// Generated by ReScript, PLEASE EDIT WITH CARE

import * as $$Navigation from "next/navigation";
import * as JsxRuntime from "react/jsx-runtime";

function MakeParams(Params) {
return {};
}

var Next = {
MakeParams: MakeParams
};

function Playground$Component(props) {
var params = $$Navigation.useParams();
return JsxRuntime.jsxs("div", {
children: [
JsxRuntime.jsx("p", {
children: "Tag: " + params.tag
}),
JsxRuntime.jsx("p", {
children: "Item: " + params.item
})
]
});
}

var Component = {
make: Playground$Component
};

export {
Next ,
Component ,
}
/* next/navigation Not a pure module */

```
</ CodeTab>

## Sharing a type with an external binding
This becomes incredibly useful when you need to have types that are unique to a project but shared across multiple components.
Let's say you want to create a library with a `getEnv` function to load in environment variables found in `import.meta.env`.
```res
@val external env: 'a = "import.meta.env"

let getEnv = () => {
env
}
```
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.
```res
type t = {"LOG_LEVEL": string}

let values: t = getEnv()
```
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.

We can instead create a module function that can return a module that has contains a `getEnv` function that has a typed response.
```res
module MakeEnv = (
E: {
type t
},
) => {
@val external env: E.t = "import.meta.env"

let getEnv = () => {
env
}
}
```
And now consumers of our library can define the types and create a custom version of the hook for their application.
Notice that in the JavaScript output that the `import.meta.env` is used directly and doesn't require any function calls or runtime overhead.

<CodeTab labels={["ReScript", "JS Output"]}>
```res
module Env = MakeEnv({
type t = {"LOG_LEVEL": string}
})

let values = Env.getEnv()
```
```js
var Env = {
getEnv: getEnv
};

var values = import.meta.env;
```
</ CodeTab>

## Shared functions
You might want to share functions across modules, like a way to log a value or render it in React.
Here's an example of module function that takes in a type and a transform to string function.

```res
module MakeDataModule = (
T: {
type t
let toString: t => string
},
) => {
type t = T.t
let log = a => Console.log("The value is " ++ T.toString(a))

module Render = {
@react.component
let make = (~value) => value->T.toString->React.string
}
}
```
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.
<CodeTab labels={["ReScript", "JS Output"]}>
```res
module Person = {
type t = { firstName: string, lastName: string }
let toString = person => person.firstName ++ person.lastName
}

module PersonData = MakeDataModule(Person)
```

```js
// Notice that none of the JS output references the MakeDataModule function

function toString(person) {
return person.firstName + person.lastName;
}

var Person = {
toString: toString
};

function log(a) {
console.log("The value is " + toString(a));
}

function Person$MakeDataModule$Render(props) {
return toString(props.value);
}

var Render = {
make: Person$MakeDataModule$Render
};

var PersonData = {
log: log,
Render: Render
};
```
</CodeTab>

Now the `PersonData` module has the functions from the `MakeDataModule`.
<CodeTab labels={["ReScript", "JS Output"]}>
```res
@react.component
let make = (~person) => {
let handleClick = _ => PersonData.log(person)
<div>
{React.string("Hello ")}
<PersonData.Render value=person />
<button onClick=handleClick>
{React.string("Log value to console")}
</button>
</div>
}
```
```js
function Person$1(props) {
var person = props.person;
var handleClick = function (param) {
log(person);
};
return JsxRuntime.jsxs("div", {
children: [
"Hello ",
JsxRuntime.jsx(Person$MakeDataModule$Render, {
value: person
}),
JsxRuntime.jsx("button", {
children: "Log value to console",
onClick: handleClick
})
]
});
}
```
</CodeTab>

## Dependency injection
Module functions can be used for dependency injection.
Here's an example of injecting in some config values into a set of functions to access a database.
<CodeTab labels={["ReScript", "JS Output"]}>
```res
module type DbConfig = {
let host: string
let database: string
let username: string
let password: string
}

module MakeDbConnection = (Config: DbConfig) => {
type client = {
write: string => unit,
read: string => string,
}
@module("database.js")
external makeClient: (string, string, string, string) => client = "makeClient"

let client = makeClient(Config.host, Config.database, Config.username, Config.password)
}

module Db = MakeDbConnection({
let host = "localhost"
let database = "mydb"
let username = "root"
let password = "password"
})

let updateDb = Db.client.write("new value")
```
```js
// Generated by ReScript, PLEASE EDIT WITH CARE

import * as DatabaseJs from "database.js";

function MakeDbConnection(Config) {
var client = DatabaseJs.makeClient(Config.host, Config.database, Config.username, Config.password);
return {
client: client
};
}

var client = DatabaseJs.makeClient("localhost", "mydb", "root", "password");

var Db = {
client: client
};

var updateDb = client.write("new value");

export {
MakeDbConnection ,
Db ,
updateDb ,
}
/* client Not a pure module */
```
</CodeTab>
28 changes: 14 additions & 14 deletions pages/docs/manual/latest/module.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -413,22 +413,22 @@ type state = int
let render: string => string
```

## Module Functions (functors)
## Module Functions

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

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

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

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

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

</CodeTab>

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

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

### Module functions types

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

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

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

## Tips & Tricks

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.
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.