voi*_*ard 7 c++ monads haskell
是否有可能表达一种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;
}
Run Code Online (Sandbox Code Playgroud)
但面临缺乏多态性.实际上它可能是我的非现行C++,因为我上次在8年前使用它.也许可以使用一些新的C++特性来表达一般的monadic接口,比如类型推断.它只是为了娱乐和解释monad对非haskellers和非数学家.
C++ 的类型系统不够强大,无法抽象更高种类的类型,但由于模板是鸭子类型的,您可以忽略这一点,只单独实现各种 Monad,然后将 Monad 操作表示为 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;
Run Code Online (Sandbox Code Playgroud)
然后就可以写类似的东西了bind(bind(make_just(6), [](int i) { return i - 2; }), [](int i) { return just("Hello, World!"[i]); })。请注意,本文中的代码不完整,因为包装的值未正确转发,一旦const涉及 -qualified 和 move-only 类型,就应该出现错误。您可以在此处查看正在运行的代码(使用 GCC 4.7),尽管这可能用词不当,因为它所做的并不是触发断言。(为未来的读者提供相同的 ideone 代码。)
解决方案的核心是just_type<T>,nothing_type或MonadicValue(内部bind)都不是单子,而是一个总体单子的某些单子值的类型 -just_type<int>并且nothing_type 一起是一个单子(有点 - 我把类型问题放在一边)现在,但请记住,可以在事后重新绑定模板专业化,例如std::allocator<T>!)。因此,bind它所接受的内容必须有些宽松,但请注意,这并不意味着它必须接受一切。
当然,完全有可能有一个类模板,M它M<T>是 的模型MonadicValue,并且bind(m, f)只有在有 type 的M<U>地方才具有 type 。从某种意义上说,这会生成monad(带有 kind ),并且代码仍然可以工作。(说到,也许适应单一界面将是一个很好的练习。)mM<T>M* -> *Maybeboost::optional<T>
精明的读者会注意到,我没有return与这里等效的东西,一切都是通过just和make_just工厂完成的,它们是构造函数的对应部分Just。这是为了保持答案简短 - 一个可能的解决方案是编写pure执行 的工作return,并返回一个可隐式转换为任何建模类型的值MonadicValue(例如通过推迟到某些MonadicValue::pure)。
不过,存在设计方面的考虑,C++ 的有限类型推导意味着它bind(pure(4), [](int) { return pure(5); })无法开箱即用。然而,这并不是一个无法克服的问题。(解决方案的一些轮廓是重载bind,但是如果我们添加到概念的接口中,那就很不方便,MonadicValue因为任何新操作也必须能够显式处理纯值;或者使纯值MonadicValue也成为其模型。)