在此article ,作者使用这个例子解释了 monad(我猜使用的是 Haskell):
bind f' :: (Float,String) -> (Float,String)
which implies that
bind :: (Float -> (Float,String)) -> ((Float,String) -> (Float,String))
然后继续要求实现函数绑定(bind)并提供解决方案:
bind f' (gx,gs) = let (fx,fs) = f' gx in (fx,gs++fs)
我在理解解决方案时遇到问题。这在 C 或 Swift 中会是什么样子?
我已经尽我所能实现了这个例子,但我仍然坚持实现绑定(bind):
let f: Float -> Float = { value in return 2 * value }
let g: Float -> Float = { value in return 10 + value }
let ff: Float -> (Float, String) = { value in return (f(value), "f called") }
let gg: Float -> (Float, String) = { value in return (g(value), "f called") }
最佳答案
在 C++ 中,我认为它看起来像这样:
#include <functional>
#include <string>
#include <utility>
using P = std::pair<float, std::string>;
using FP = std::function<P(P)>;
FP mbind(std::function<P(float)> f) {
return [f](P in) {
auto && res = f(in.first);
return {res.first, in.second + res.second};
};
}
在 C 中,您可以通过存储函数指针来执行类似的操作,但调用语法必须更加冗长,因为您需要显式传递状态。
关于c - 了解绑定(bind)功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34233993/