Skip to content

Add docs and syntax lookup for scoped polymorphic types #693

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
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion data/sidebar_manual_latest.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
"reserved-keywords"
],
"Advanced Features": [
"extensible-variant"
"extensible-variant",
"scoped-polymorphic-types"
],
"JavaScript Interop": [
"interop-cheatsheet",
Expand Down
54 changes: 54 additions & 0 deletions misc_docs/syntax/language_scoped_polymorphic_type.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
---
id: "scoped-polymorphic-type"
keywords: ["scoped", "polymorphic"]
name: "'a."
summary: "This is a `scoped polymorphic type`."
category: "languageconstructs"
---

In ReScript, polymorphic functions can only deal with one specific type. When they are called, their type gets fixed.
For instance this logging function is bound in a polymorphic way as you can see by the type parameter (`'a`).

```res
type logger<'a> = { log: 'a => unit}

@module("jsAPI") external getLogger: unit => logger<'a> = "getLogger"

let myLogger = getLogger()

myLogger.log("Hello, ReScript!")
myLogger.log(42) // Type error!
```

Scoped polymorphic types make such behavior possible, in a type-safe way. See the `'a.` in the example below.

### Example

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

```res
type logger = { log: 'a. 'a => unit}

@module("jsAPI") external getLogger: unit => logger = "getLogger"

let myLogger = getLogger()

myLogger.log("Hello, ReScript!")
myLogger.log(42) // Ok!
```

```js
var JsAPI = require("jsAPI");

var myLogger = JsAPI.getLogger();

myLogger.log("Hello, ReScript!");

myLogger.log(42);
```

</CodeTab>

### References

- [Scoped Polymorphic Types](/docs/manual/latest/scoped-polymorphic-types)
86 changes: 86 additions & 0 deletions pages/docs/manual/latest/scoped-polymorphic-types.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
---
title: "Scoped Polymorphic Types"
description: "Scoped Polymorphic Types in ReScript"
canonical: "/docs/manual/latest/scoped-polymorphic-types"
---

# Scoped Polymorphic Types

Scoped Polymorphic Types in ReScript are functions with the capability to handle arguments of any type within a specific scope. This feature is particularly valuable when working with JavaScript APIs, as it allows your functions to accommodate diverse data types while preserving ReScript's strong type checking.

## Definition and Usage

Scoped polymorphic types in ReScript offer a flexible and type-safe way to handle diverse data types within specific scopes. This documentation provides an example to illustrate their usage in a JavaScript context.

### Example: Logging API

Consider a logging example within a JavaScript context that processes various data types:

```js
const logger = {
log: (data) => {
if (typeof data === "string") {
/* handle string */
} else if (typeof data === "number") {
/* handle number */
} else {
/* handle other types */
}
},
};
```

In ReScript, we can bind to this function as a record with a scoped polymorphic function type:

```res prelude
type logger = { log: 'a. 'a => unit }

@module("jsAPI") external getLogger: unit => logger = "getLogger"
```

The `logger` type represents a record with a single field `log`, which is a scoped polymorphic function type `'a. 'a => unit`. The `'a` indicates a type variable that can be any type within the scope of the `log` function.

Now, we can utilize the function obtained from `getLogger`:

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

```res example
let myLogger = getLogger()

myLogger.log("Hello, ReScript!")
myLogger.log(42)
```

```js
var myLogger = JsAPI.getLogger();

myLogger.log("Hello, ReScript!");
myLogger.log(42);
```

</CodeTab>

In this example, we create an instance of the logger by calling `getLogger()`, and then we can use the `log` function on the `myLogger` object to handle different data types.

## Limitations of Normal Polymorphic Types

Let's consider the same logging example in ReScript, but this time using normal polymorphic types:

```res
type logger<'a> = { log: 'a => unit}

@module("jsAPI") external getLogger: unit => logger<'a> = "getLogger"
````

In this case, the `logger` type is a simple polymorphic function type `'a => unit`. However, when we attempt to use this type in the same way as before, we encounter an issue:

```res
let myLogger = getLogger()

myLogger.log("Hello, ReScript!")
myLogger.log(42) // Type error!
```

The problem arises because the type inference in ReScript assigns a concrete type to the `logger` function based on the first usage. In this example, after the first call to `myLogger`, the compiler infers the type `logger<string>` for `myLogger`. Consequently, when we attempt to pass an argument of type `number` in the next line, a type error occurs because it conflicts with the inferred type `logger<string>`.

In contrast, scoped polymorphic types, such as `'a. 'a => unit`, overcome this limitation by allowing type variables within the scope of the function. They ensure that the type of the argument is preserved consistently within that scope, regardless of the specific value used in the first invocation.