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
typeclass expects a generic parameter F
that itself can have another generic parameter.
In scala, it is already possible to do that with the following syntax:
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<int>
). This feature allows defining functions like the following:
def foldLeft[A, B](fa: F[A], b: B)(f: (B, A) => B): B
If F
is List
then:
B foldLeft<A, B>(List<A> fa, B b, B Function(B, A) f);
This is not possible currently in dart. The fa
parameter cannot itself accept another generic parameter.
/// Not valid dart code!
abstract class Foldable<F<_>> {
B foldLeft<A, B>(F<A> fa, B b, B Function(B, A) f);
}
/// Not valid dart code!
abstract class Foldable<F> {
// Error: The type 'F' is declared with 0 type parameters, but 1 type arguments were given.
B foldLeft<A, B>(F<A> 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:
abstract class Foldable<TypeClass, TypeData> {
TypeClass bind<B>(covariant TypeClass Function(TypeData a) f);
}
/// Missing type parameter on IList!
class IList<Data> extends Foldable<IList, Data> {
@override
IList bind<B>(covariant IList Function(Data a) f) {}
}
In this example, the return type is a generic IList<dynamic>
, 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?