有一次,我以为我理解Monad。然而,当我试图将我对代码的理解与理论联系起来时,我发现自己仍然不清楚。所以这里是:
第1部分:是流行的教育链接a-monad-is-just-a-monoid-in-the-category-of-endofunctors-whats-the-problem。
我的问题:
第2部分.这里是另一个链接不,真的,什么是单曲?,我最初发现它非常有指导意义。然而,最近我发现我无法清楚地将其示例中的代码映射到正式定义中。我对Haskell的经验有限,所以我只关注它的c++示例代码。这是作者声称是单曲的那个。
#include <iostream>
#include <string>
using namespace std;
string ret(string x) {
return "[" + x + "]";
}
string bind(string x, string (*func) (string)) {
return "[" + func(x.substr(1, x.length() - 2)) + "]";
}
string step1(string x) {
return "Hello " + x;
}
string step2(string x) {
return x + ", monads aren't that complicated.";
}
string step3(string x) {
return "***" + x + "***";
}
template<typename T> T run(T (*ret) (string),
T (*bind) (T, string (*) (string))) {
T x = "friend";
// first, wrap up the value of x
x = ret(x);
// now use wrapCall to run each step
x = bind(x, step1);
x = bind(x, step2);
x = bind(x, step3);
return x;
}
int main() {
cout << run<string>(ret, bind) << "\n";
}然后作者说:
信不信由你,我们刚刚写了一个单曲(具体来说,monad是绑定和ret的对子)!
我的问题:
string ret(string x)是否对应于e中的单半群定义?但是e应该适用于集合S元素。step1, step2, step3是。然而,它们看起来不是函子,而是范畴。因为它们就像链接对象的箭头(输入string到type string)。一个函子应该把两个类别联系起来。bind是操作*(自然变换μ:t×T→T)吗?希望我能说出我的困惑,任何帮助都是感激的。
发布于 2022-05-14 05:16:16
我想我已经搞清楚了。让我自己回答这个问题。在我发布的C++代码中,[]是类型构造函数,bind函数对应于Haskell中的fmap,因此它们形成了一个函子,这是这里提到的T a-monad-is-just-a-monoid-in-the-category-of-endofunctors-whats-the-problem。
ret函数是自然变换,η。run实际上代表了自然的转换,μ。
https://stackoverflow.com/questions/72218331
复制相似问题