在c ++ 11中实现Haskell的Maybe Monad [英] Implementing Haskell's Maybe Monad in c++11
问题描述
我试图使用C ++ 11中的lambda函数和模板实现Haskell的Maybe monad。这是我到目前为止
I am trying to implement the Maybe monad from Haskell using the lambda functions in C++11 and templates. Here's what I have so far
#include<functional>
#include<iostream>
using namespace std;
template<typename T1>
struct Maybe
{
T1 data;
bool valid;
};
template<typename T1, typename T2>
Maybe<T2> operator>>=(Maybe<T1> t, std::function < Maybe<T2> (T1)> &f)
{
Maybe<T2> return_value;
if(t.valid == false)
{
return_value.valid = false;
return return_value;
}
else
{
return f(t.data);
}
}
int main()
{
Maybe<int> x = {5, true};
Maybe<int> y = {29, false};
auto z = [](int a) -> Maybe<int>
{
Maybe<int> s;
s.data = a+1;
s.valid = true;
return s;
};
Maybe<int> p = (x >>= z);
Maybe<int> q = (y >>= z);
cout<<p.data<<' '<<p.valid<<endl;
cout<<q.data<<' '<<q.valid<<endl;
}
当涉及到实际的> =
调用,我得到一个编译器错误,说没有匹配找到>> =
运算符。是我对C ++ 11的lambda函数的理解失败了吗?
When it comes to the actual >>=
call, I am getting a compiler error saying that no match found for >>=
operator. Is my understanding of C++11's lambda functions failing me here?
推荐答案
lambda的类型不是一个特殊化 std :: function
。它是一些无名的类型。有一个转换为 std :: function
,但这意味着类型扣除将不起作用。所以,在这个调用:
The type of a lambda isn't a specialization of std::function
. It's some unamed type. There is a conversion to std::function
, but that means type deduction won't work for it. So, in this call:
Maybe<int> p = (x >>= z);
无法推导类型 T2
:
Maybe<T2> operator>>=(Maybe<T1> t, std::function < Maybe<T2> (T1)> &f)
从一开始就将lambda存储在 std :: function
变量中,它应该工作:
Store the lambda in a std::function
variable from the start, and it should work:
std::function < Maybe<int> (int)> z = [](int a) -> Maybe<int> { ... };
但是,它可能更容易接受任何类型的函数对象。这样,您仍然可以使用 auto
作为lambda。
However, it's probably easier to accept any kind of function object. That way you can still use auto
for the lambda.
template<typename T1, typename F>
typename std::result_of<F(T1)>::type
operator>>=(Maybe<T1> t, F&& f) {
... std::forward<F>(f)(t.data);
}
这篇关于在c ++ 11中实现Haskell的Maybe Monad的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!