c - 了解绑定(bind)功能

标签 c swift haskell functional-programming monads

在此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/

相关文章:

c - 数组是按值传递还是按引用传递?

c++ - 无法从 C 应用程序访问 C++ DLL 中的变量

c - 变量在 if else 循环之前正确打印,但在 if else 循环中不保留该值

ios - 调整 UITableViewCell 大小以适合标签或图像和圆角

swift - 存储自定义类的数组的数组 - Swift

haskell - 由内而外构建管道代理

c - 如何编译这段代码?

ios - Swift 4 : iOS Simulator wrong identifier (iPhone 5s, iOS 11) 使用 ProcessInfo().environment ["SIMULATOR_MODEL_IDENTIFIER"]

haskell - 如何根据列表的后半部分简洁地匹配列表,并相应地绑定(bind)它的前半部分?

haskell - 我们可以为 WrappedArrow 定义一个 Monad 实例吗?