在C ++中表达一般的monadic接口(如Monad类)

时间:2012-12-07 07:10:22

标签: c++ haskell monads

甚至可以表达一种monad“C ++? 我开始写这样的东西,但卡住了:

#include <iostream>

template <typename  a, typename b> struct M;

template <typename a, typename b> struct M {
    virtual M<b>& operator>>( M<b>& (*fn)(M<a> &m, const a &x) ) = 0;
};

template <typename a, typename b> 
struct MSome : public M<a> {
    virtual M<b>& operator>>( M<a>& (*fn)(M<a> &m, const a &x) ) {
        return fn(*this, x);
    }

private:
    a x;
};

M<int, int>& wtf(M<int> &m, const int &v) {
    std::cout << v << std::endl;
    return m;
}

int main() {
//    MSome<int> v;
//    v >> wtf >> wtf;
    return 0;
}

但面临缺乏多态性。实际上它可能是我的非现行C ++,因为我上次在8年前使用它。也许可以使用一些新的C ++特性来表达一般的monadic接口,比如类型推断。这只是为了娱乐和解释monad对非haskellers和非数学家。

2 个答案:

答案 0 :(得分:3)

  

C ++'类型系统不足以抽象出更高级别的类型,但由于模板是鸭子类型,你可以忽略它,只是单独实现各种Monads,然后将单一操作表达为SFINAE模板。丑陋,但它是最好的。

这条评论对这笔钱很感兴趣。我一次又一次地看到人们试图使模板特化“协变”和/或滥用继承。无论好坏,面向概念的通用编程在我看来都是理所当然的。这是一个快速演示,它将使用C ++ 11的功能以简洁明了,尽管它应该可以在C ++ 03中实现相同的功能:

(*:对于竞争性观点,请参阅我的报价中的“丑陋,但最好的”!)

#include <utility>
#include <type_traits>

// SFINAE utility
template<typename...> struct void_ { using type = void; };
template<typename... T> using Void = typename void_<T...>::type;

/*
 * In an ideal world std::result_of would just work instead of all that.
 * Consider this as a write-once (until std::result_of is fixed), use-many
 * situation.
 */    
template<typename Sig, typename Sfinae = void> struct result_of {};
template<typename F, typename... Args>
struct result_of<
    F(Args...)
    , Void<decltype(std::declval<F>()(std::declval<Args>()...))>
> {
    using type = decltype(std::declval<F>()(std::declval<Args>()...));
};
template<typename Sig> using ResultOf = typename result_of<Sig>::type;

/*
 * Note how both template parameters have kind *, MonadicValue would be
 * m a, not m. We don't whether MonadicValue is a specialization of some M<T>
 * or not (or derived from a specialization of some M<T>). Note that it is
 * possible to retrieve the a in m a via typename MonadicValue::value_type
 * if MonadicValue is indeed a model of the proper concept.
 *
 * Defer actual implementation to the operator() of MonadicValue,
 * which will do the monad-specific operation
 */
template<
    typename MonadicValue
    , typename F
    /* It is possible to put a self-documenting assertion here
       that will *not* SFINAE out but truly result in a hard error
       unless some conditions are not satisfied -- I leave this out
       for brevity
    , Requires<
        MonadicValueConcept<MonadicValue>
        // The two following constraints ensure that
        // F has signature a -> m b
        , Callable<F, ValueType<MonadicValue>>
        , MonadicValueConcept<ResultOf<F(ValueType<MonadicValue>)>>
    >...
    */
>
ResultOf<MonadicValue(F)>
bind(MonadicValue&& value, F&& f)
{ return std::forward<MonadicValue>(value)(std::forward<F>(f)); }

// Picking Maybe as an example monad because it's easy
template<typename T>
struct just_type {
    using value_type = T;

    // Encapsulation omitted for brevity
    value_type value;

    template<typename F>
    // The use of ResultOf means that we have a soft contraint
    // here, but the commented Requires clause in bind happens
    // before we would end up here
    ResultOf<F(value_type)>
    operator()(F&& f)
    { return std::forward<F>(f)(value); }
};

template<typename T>
just_type<T> just(T&& t)
{ return { std::forward<T>(t) }; }

template<typename T>
just_type<typename std::decay<T>::type> make_just(T&& t)
{ return { std::forward<T>(t) }; }

struct nothing_type {
    // Note that because nothing_type and just_type<T>
    // are part of the same concept we *must* put in
    // a value_type member type -- whether you need
    // a value member or not however is a design
    // consideration with trade-offs
    struct universal { template<typename T> operator T(); };
    using value_type = universal;

    template<typename F>
    nothing_type operator()(F const&) const
    { return {}; }
};
constexpr nothing_type nothing;

然后可以编写类似bind(bind(make_just(6), [](int i) { return i - 2; }), [](int i) { return just("Hello, World!"[i]); })的内容。请注意,此帖子中的代码不完整,因为包装的值未正确转发,只要涉及const - 限定和仅限移动类型,就应该出现错误。您可以看到代码在运行中(使用GCC 4.7)here,尽管这可能是用词不当,因为它所做的一切都不是触发断言。 (Same code on ideone面向未来的读者。)

解决方案的核心是just_type<T>nothing_typeMonadicValue(内部bind)都不是monad,而是一些monadic值的类型monad - just_type<int>nothing_type 在一起是一个monad(有点 - 我现在把它放在一边,但请记住,有可能例如,事后重新绑定模板特化,例如std::allocator<T>!)。因此bind在接受的内容中必须有点宽容,但请注意这并不意味着它必须接受所有内容。

当然,完全有可能拥有一个类模板MM<T>MonadicValue的模型,而bind(m, f)只有M<U>类型其中m的类型为M<T>。从某种意义上说,这将使M monad(具有种类* -> *),并且代码仍然有效。 (说到Maybe,或许调整boost::optional<T>来建立一个monadic接口将是一个很好的练习。)

精明的读者会注意到我在这里没有等效的return,所有工作都是在justmake_just工厂完成的,这些工厂是Just的对应工具。 1}}构造函数。这是为了保持答案简短 - 一个可能的解决方案是编写一个pure来完成return的工作,并返回一个可隐式转换为任何模型{{1}的类型的值(例如,推迟到某些MonadicValue)。

有一些设计考虑因素,因为C ++的有限类型推导意味着MonadicValue::pure无法开箱即用。然而,这不是一个不可逾越的问题。 (解决方案的一些概述是重载bind(pure(4), [](int) { return pure(5); }),但如果我们添加到bind概念的接口,这是不方便的,因为任何新操作也必须能够明确地处理纯值;或者制作纯值也是MonadicValue的模型。)

答案 1 :(得分:0)

我会这样做:

template<class T>
class IO {
public:
   virtual T get() const=0;
};

template<class T, class K>
class C : public IO<K> {
public:
   C(IO<T> &io1, IO<K> &io2) : io1(io1), io2(io2) { }
   K get() const { 
      io1.get();
      return io2.get();
   }
private:
  IO<T> &io1;
  IO<K> &io2;
};

int main() {
  IO<float> *io = new YYYY;
  IO<int> *io2 = new XXX;
  C<float,int> c(*io, *io2);
  return c.get();
}