In this article, the author explains monad using this example (I am guessing Haskell is used):
bind f' :: (Float,String) -> (Float,String)
which implies that
bind :: (Float -> (Float,String)) -> ((Float,String) -> (Float,String))
and proceed to ask to implement the function bind and offer the solution as:
bind f' (gx,gs) = let (fx,fs) = f' gx in (fx,gs++fs)
I am having problem understanding the solution. What would this look like in C or Swift?
I have gone as far as I can implementing the example and I am stuck at implementing 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") }
In C++ I think it would look something like this:
#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};
};
}
In C you could do something similar by storing function pointers, though the invocation syntax would have to be more verbose since you'll need to pass the state around explicitly.
In Swift, perhaps something like this:
let bind: (Float -> (Float, String)) -> ((Float, String) -> (Float, String)) = {
lhs in
return {
rhs in
let result = lhs(rhs.0)
return (result.0, "\(result.1); \(rhs.1)" )
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With