首页 文章

C语言较高的类型

提问于
浏览
43

这个问题适用于了解Haskell(或任何其他支持高级类型的功能语言)和C ...

是否可以使用C模板对更高级的kinded类型进行建模?如果是,那怎么样?

EDIT :

来自Tony Morris的this演讲:

Higher-order Polymorphism :

  • Java和C#等语言具有一阶多态性,因为它们允许我们对类型进行抽象 . 例如 List<A> 可以有 reverse 函数,适用于任何元素类型( A ) .

  • 更多实用的编程语言和类型系统允许我们在类型构造函数上进行抽象 .

  • 此功能称为高阶(或更高阶)多态 .

Example :

伪Java,发明了高阶多态性的符号

interface Transformer<X, Y> {
  Y transform(X x);
}

interface Monad<M> { // M :: * -> *
  <A> M<A> pure(A a);
  <A, B> M<B> bind(Transformer<A, M<B>> t, M<A> a);
}

2 回答

  • 62

    模板模板参数?

    template <template <typename> class m>
    struct Monad {
        template <typename a>
        static m<a> mreturn(const a&);
    
        template <typename a, typename b>
        static m<b> mbind(const m<a>&, m<b>(*)(const a&));
    };
    
    template <typename a>
    struct Maybe {
        bool isNothing;
        a value;
    };
    
    template <>
    struct Monad<Maybe> {
        template <typename a>
        static Maybe<a> mreturn(const a& v) {
            Maybe<a> x;
            x.isNothing = false;
            x.value = v;
            return x;
        }
    
        template <typename a, typename b>
        static Maybe<b> mbind(const Maybe<a>& action, Maybe<b>(*function)(const a&)) {
            if (action.isNothing)
                return action;
            else
                return function(action.value);
        }
    };
    
  • 3

    通常不是普通模板已经是更高级的类型?例如, std::vector 采用类型参数来创建实际类型,如 std::vector<int> ,因此它具有类型 * -> * .

相关问题