我是 D 新手,我正在寻找一种使用类似 Haskell 的类型类进行编程的好方法,例如D 中的函子、幺半群等。
Tango 或 Phobos 中是否实现了类似的功能?
我听说过可以对某些属性进行编译时类型检查的特征。它们可以用于类型类吗?
我尝试了一些模板专业化并提出了这个:
// Monoid.d
// generic Monoid gets called when there is no instance of Monoid for Type T
class Monoid(T) {
pragma(msg, "Type is not a Monoid");
}
// Monoid instance for double
class Monoid(T:double) {
static T mzero() { return 0; }
static T mappend(T a, T b ) { return a + b;}
}
// Monoid instance for int
class Monoid(T:int) {
static T mzero() { return 0; }
static T mappend(T a, T b ) { return a + b;}
}
类型参数需要为 Monoid 的通用算法可以表示为:
template genericfunctions() {
T TestMonoid(T,N = Monoid!T)(T a) {
return N.mappend(N.mzero(),a);
}
}
然而,如果你想省略模板参数,你必须导入所有需要的 Monoid 实例并混合genericfunctions
模板。
import Monoid;
import std.stdio;
import std.conv;
mixin genericfunctions;
void main() {
writefln(to!string(TestMonoid(3)));
writefln(to!string(TestMonoid(3.3243)));
}
您现在可以使用整数和双精度数作为 Monoids。
然而,当你有像 Functor 这样的类型类,其实例本身是通用的时,事情会变得更加复杂:
module Functors;
// generic Functor like generic Monoid
class Functor(alias T, A) {
pragma(msg,"Not an instance of Functor");
}
// very simple container to demonstrate functors behavior
class FunctorTest(A) {
public A a;
this(A a) {
this.a = a;
}
}
// instance of Functor for FunctorTest!A
class Functor(alias T:FunctorTest,A) {
static T!B fmap(B)(T!A a, B delegate(A) fn) {
return new T!B(fn(a.a));
}
}
一种算法如下所示:
template genericfunctions() {
T TestMonoid(T,N = Monoid!T)(T a) {
return N.mappend(N.mzero(),a);
}
// F is the Functor, A the functors type before,
// B the functors Type after, N is the instance of Functor
F!B fmap(alias F,A,B,N=Functor!(F,A))(F!A a, B delegate(A) fn) {
return N.fmap!B(a,fn);
}
}
幸运的是,您在使用它时可以省略四个模板参数:
mixin genericfunctions;
void main() {
auto a = new FunctorTest!int(3);
auto b = fmap(a,(int b) {return b+ 0.5;});
writefln(to!string(b.a));
}
但是,当您想使用另一个 Functor 实例作为 Type 时,您必须指定 fmap 的所有 4 个类型参数。有没有一种方法只需要指定实例,其他参数就可以从中推导出来?
除了笨拙的 mixin 解决方法之外,还有其他选择吗?
这种方法还有其他我没有看到的缺点吗?
那其他方法呢?
感谢您阅读本文并花时间思考和回答:)
Edit:
是否可以使用 D 中的单元测试来定义像函子法则这样的约束?那肯定很不错。