dart-lang / dart-lang/language

Adding higher-order type constructor to dart

Open
#1,655 4 comments 30 reactions 0 assignees View on GitHub
feature
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

While working on a functional programming package for dart I found that dart does not support **higher-order type constructors** (**higher-kinded type**).

For example, a typical [`Foldable`](https://github.com/typelevel/cats/blob/ddc8a0a2039bd07206b86754f22accb605f13575/core/src/main/scala/cats/Foldable.scala#L34) typeclass expects a _generic parameter_ `F` that itself can have **another** generic parameter.

In scala, [it is already possible](https://stackoverflow.com/a/6417328/7033357) to do that with the following syntax:
```scala
trait Foldable[F[_]]
```
As a concrete example, the type `F` can be a `List` and `[_]` means that the `List` can itself accept any type (e.g. `List`). This feature allows defining functions like the following:
```scala
def foldLeft[A, B](fa: F[A], b: B)(f: (B, A) => B): B
```
If `F` is `List` then:
```dart
B foldLeft(List fa, B b, B Function(B, A) f);
```

This is not possible currently in dart. The `fa` parameter cannot itself accept another generic parameter.
```dart
/// Not valid dart code!
abstract class Foldable> {
B foldLeft(F
fa, B b, B Function(B, A) f);
}

/// Not valid dart code!
abstract class Foldable {
// Error: The type 'F' is declared with 0 type parameters, but 1 type arguments were given.
B foldLeft(F
fa, B b, B Function(B, A) f);
}
```

A workaround would be to define two generic types on the same class like in the following example:
```dart
abstract class Foldable {
TypeClass bind(covariant TypeClass Function(TypeData a) f);
}

/// Missing type parameter on IList!
class IList extends Foldable {
@override
IList bind(covariant IList Function(Data a) f) {}
}
```
In this example, the return type is a generic `IList`, since it is not possible to statically define a type parameter of another generic type.

Is it possible to implement this feature in the dart language?

Contributor guide

Open the contributing guide

Research direction

Start with the Foldable examples and the proposed Dart syntax in the issue, comparing them with the linked Scala example. Done means establishing whether higher-kinded types can be added to Dart and defining the required generic behavior and syntax.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.